Search code examples
iosxcodelocalizationswiftuilocalizable.strings

Localization SwiftUI


I want to ask about localization in SwiftUI for my app but something doesnt work. I maked everything as in the example but for some reason nothing works: https://benoitpasquier.com/localization-swiftui-how-top-preview-localized-content/

This code doesnt work:

.environment(\.locale, .init(identifier: "en"))

without any code just adding Localizable (English) I translate the text in the app into English. And when I try to translate for apps in, say, English and Spanish, I have it automatically translated to English(so the default language was chosen by the system). How do I fix this so that the text is translated using the code at the top?


Solution

  • You can use LocalizedStringKey:

    In your app:

    let greeting: LocalizedStringKey = "Greeting"
    let text = Text(greeting)
    

    In your English Localizable.strings file:

    "Greeting" = "Hello";
    

    In your Spanish Localizable.strings file:

    "Greeting" = "Hola";