我必须让用户从列表中选择应用程序的语言。
将下一行放入 SceneDelegate 工作正常,因为它在开头加载指定的语言:
window.rootViewController = UIHostingController(rootView: ContentView().environment(\.locale, .init(identifier: "de")))
但我不知道如何从包含列表的 View 中设置区域设置以在整个应用程序中切换语言。
谢谢你的帮助
最佳答案
您可以使用 @State var
作为区域设置标识符。在这个例子中,我使用按钮来改变状态,文本会立即改变。
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))
}
}
在我的 Localizable.strings 中,我添加了
"Test" = "My english text";
英语和 "Test" = "Mon texte français";
对于法语。
关于swiftui - 带有 SwiftUI : How to change the environment locale on the fly 的 Swift 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61480680/