I have a bilingual app. I’ve implemented Localizable.strings, and generally, when I switch the language, it changes everywhere except for the navigation bar. When I navigate to a different view that also has a navigation bar title, the language changes, but when I go back and try to change the language again, the navigation bar title doesn't update. In other parts of the app, like TabView, the language change and works perfectly. Does anyone know how to solve this issue?
struct CategoryView: View {
@AppStorage("selectedLanguage") private var selectedLanguage: String = "pl"
var body: some View {
NavigationStack {
Text("Category")
Button("ChnageLanguageEn") {
selectedLanguage = "en"
}
Button("ChnageLanguagePl") {
selectedLanguage = "pl"
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle("Category")
}
}
}
@main
struct iOSApp: App {
@AppStorage("selectedLanguage") private var selectedLanguage: String = Locale.current.language.languageCode?.identifier ?? "pl"
@StateObject var themeViewModel = ThemeViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.locale, .init(identifier: selectedLanguage))
.environmentObject(themeViewModel)
.preferredColorScheme(themeViewModel.getColorScheme())
}
}
}
In .navigationTitle, I tried using .navigationTitle("Category") or .navigationTitle(LocalizedStringKey("Category")) or .navigationTitle(Text("Category")), but neither had any effect.
It seems that the view does not refresh the NavigationStack/navigationTitle
when the language is changed, at least more than once.
So try this approach to force it to refresh using an .id(UUID())
.
struct CategoryView: View {
@AppStorage("selectedLanguage") private var selectedLanguage: String = "pl"
var body: some View {
NavigationStack {
Text("Category")
Button("Change Language to English") {
selectedLanguage = "en"
}
Button("Change Language to Polish") {
selectedLanguage = "pl"
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle("Category")
}
.id(UUID()) // <--- here
.environment(\.locale, Locale(identifier: selectedLanguage))
}
}