How to implement localization in Swift UI

回眸只為那壹抹淺笑 提交于 2020-01-02 06:14:28

问题


Can anybody help me? I can't find any description of the localization in Swift UI. Can anyone please give advice or better an example of how to localize for example Text()?


回答1:


When you look at documentation for Text you can see that it takes LocalizedStringKey not a String into its initializer:

init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)

It make localizing very straightforawar. All you have to do is:

  • create a new file of type Strings File, call it Localizable
  • select the new file and naigate to File Inspector in the right hand side panel and click Localize...
  • go to your project file to the Localizations section and add another language to the list - Xcode will create localization files for you

When you select you Localizable.strings you will see that it contains files for the original language and the language you have just added. That's where you put your translations, i.e. key - localized text pairs.

If you have a text like this is your app:

Text("Hello World!")

You have to now add to your Localizable.strings your translations:

for your base language:

"Hello World!" = "Hello World!";

and for your second language (in this case German):

"Hello World!" = "Hallo Welt!";

To see your previews localised you can define them like this:

struct ContentViewView_Previews: PreviewProvider {

    static var previews: some View {
        ForEach(["en", "de"], id: \.self) { id in
            ContentView()
                .environment(\.locale, .init(identifier: id))
        }
    }
}



回答2:


For swift UI file, you just need to insert string key from localization .strings file

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("selectLanguage")
            Text("languagesList")
        }



    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environment(\.locale, .init(identifier: "en"))
    }
}

and this is an example from .strings file

"selectLanguage" = "Select language";
"languagesList" = "Languages list";

result is here



来源:https://stackoverflow.com/questions/58578341/how-to-implement-localization-in-swift-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!