3

I have to let the user to choose the language of the app from a list.

Putting the next line in the SceneDelegate works fine because it loads the specified language at the beginning:

window.rootViewController = UIHostingController(rootView: ContentView().environment(\.locale, .init(identifier: "de")))

but I don't know how to set the locale from the view that contain the list to switch the language in the whole app.

Thanks for any help

BartBart
  • 31
  • 1
  • 2

2 Answers2

12

You can use a @State var as the locale identifier. In this exemple, I use buttons to change the State, and the Text changes instantly.

struct LanguageView: View {
    @State var identifier = "en"

    var body: some View {
        VStack {
            Button("French", action: {
                self.identifier = "fr"
            })
            Button("English", action: {
                self.identifier = "en"
            })
            Text("Test")
        }
        .environment(\.locale, .init(identifier: identifier))
    }
}

And in my Localizable.strings I've added "Test" = "My english text"; for English and "Test" = "Mon texte français"; for French.

Nicolas Mandica
  • 803
  • 1
  • 10
  • 16
0

Using the environment view modifier to change the locale affects many localizations, but not all. It does not affect lookup in localized Image Sets, calls to Bundle.main.localizedString, or calls to NSLocalizedString. I'm not sure if these are considered bugs.

Mark Volkmann
  • 909
  • 12
  • 15