有人可以帮我吗?我找不到任何Swift UI中本地化的描述。 请问有人能否给出建议或更好的示例,例如如何本地化Text()
?
有人可以帮我吗?我找不到任何Swift UI中本地化的描述。 请问有人能否给出建议或更好的示例,例如如何本地化Text()
?
当您查看 Text 的文档时,可以看到它在初始化函数中接受的是 LocalizedStringKey
而不是 String
:
init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)
这使得本地化变得非常简单明了。您需要做的就是:
Localizable.strings
当您选择您的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))
}
}
}
有一件事情,任何我看到的解释都没有很清楚地表明你可能做错的事情。结果证明,只有在传递字面值时,Text("hello")才会被解释为本地化键。如果传递字符串类型的变量,则不会发生这种情况。答案是将变量声明为类型LocalizedStringKey。
Text("hello") //-> implicitly treats string literal as a key; looks up and displays "Hello World!"
let cap1:String = "hello"
Text(cap1) //-> no lookup for explicit String variable; just displays "hello"
let cap2:LocalizedStringKey = "hello"
Text(cap2) //-> looks up explicit LocalizedStringKey value; displays "Hello World!"
在将字符串传递给Text()之前,您可以将其简单地包装在LocalizedStringKey中。
Localizable.strings文件:
"Dismiss" = "关闭";
"Cancel" = "取消";
SwiftUI 视图文件:
Text(LocalizedStringKey("Dismiss"))
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"))
}
}
"selectLanguage" = "Select language";
"languagesList" = "Languages list";
这里是结果:
要本地化您的应用程序,您需要:
要在SwiftUI中使用Localizable,您可以采用以下方式:
导入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)
}
struct Localized: View {
var text: String
var arg: Any?
var body: some View {
if let arg = arg {
if let arg = arg as? [Any] {
Text(String(format: NSLocalizedString(text, comment: ""), arg.compactMap({String(describing:$0)}).joined(separator: " ")).replacingOccurrences(of: "(null)", with: ""))
} else {
Text(String(format: NSLocalizedString("\(text) %@", comment: ""), String(describing: arg)))
}
} else {
Text(LocalizedStringKey(text))
}
}
}
使用方法:
Localized(text: "hello")
Localized(text: "this %@ %@", arg: [4, "a"])