Answers:
查看Text文档时,您会发现它将LocalizedStringKey而不是String放入其初始化程序中:
init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)
它使本地化非常简单。您要做的就是:
当您选择Localizable.strings时,您将看到它包含原始语言和刚添加的语言的文件。那是您放置翻译的地方,即键-本地化的文本对。
如果您有这样的文字是您的应用程序:
Text("Hello World!")
您现在必须将翻译添加到Localizable.strings中:
对于您的基本语言:
"Hello World!" = "Hello World!";
对于您的第二种语言(在这种情况下为德语):
"Hello World!" = "Hallo Welt!";
要查看已本地化的预览,可以这样定义它们:
struct ContentViewView_Previews: PreviewProvider {
static var previews: some View {
ForEach(["en", "de"], id: \.self) { id in
ContentView()
.environment(\.locale, .init(identifier: id))
}
}
}
对于快速的UI文件,您只需要从本地化.strings文件中插入字符串键
导入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"))
}
}
这是来自.strings文件的示例
"selectLanguage" = "Select language";
"languagesList" = "Languages list";
结果在 这里
要在SwiftUI中使用Localazable,您可以执行以下方式:
导入SwiftUI以在文件中使用LocalizedStringKey
//MARK: - File where you enum your keys to your Localized file
enum ButtonName: LocalizedStringKey {
case submit
case cancel
}
//MARK: - Your Localized file where are your translation
"submit" = "Submit is pressed";
"cancel" = "Cancel";
//MARK: - In your code
let submitButtonName = ButtonName.submit.rawValue
let cancelButtonName = ButtonName.cancel.rawValue
VStack {
Text(submitButtonName)
Text(cancelButtonName)
}