swift - 如何在 SwiftUI 中本地化多个视图
问题描述
我是 SwiftUI 的新手,我的应用也需要功能翻译语言,所以我先创建了一个示例应用,然后再将此功能整合到我的其他项目中。因此,正如您在下面的代码中看到的那样,我可以通过单击按钮来更改语言,并且它可以完美运行,但我不知道这将如何与多个视图一起使用。我希望将所有这些本地化并希望删除冗余。
import SwiftUI
struct ContentView: View {
@State var title = ""
var body: some View {
VStack{
Text(title)
.padding()
Button {
title = "welcomeTitle".localizableString("en")
} label: {
Text("EN")
}
Button {
title = "welcomeTitle".localizableString("ja")
} label: {
Text("JA")
}
}
.onAppear {
// title = "welcomeTitle".localizableString("en")
if(Bundle.main.preferredLocalizations.first == "ja"){
title = "welcomeTitle".localizableString("ja")
}
else{
title = "welcomeTitle".localizableString("en")
}
}
}
}
extension String {
func localizableString(_ name: String) -> String {
let path = Bundle.main.path(forResource: name, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
解决方案
见此之前
然后是一个方便的扩展:
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
}
//For your button
Button {
//action
} label: {
Text("welcomeTitle".localized)
}
在您的 Localizable.strings 文件 English 中,添加以下内容:
"welcomeTitle" = "welcomeTitle EN";
在 Localizable.strings 文件日文中,添加以下内容:
"welcomeTitle" = "welcomeTitle JA";
推荐阅读
- ios - Best Approach for maintaining configuration safely
- php - Codeception, write acceptance tests with the pageObject design pattern and gherkin
- iterator - Lifetime inference problem when implementing iterator with refs
- android - Ask for location permission again after user says no the first time
- python - 计算熊猫数据框中同一天发生的列表中的常见元素
- typescript - TypeScript require one parameter or the other, but not neither
- typescript - ko.mapping || 无法读取未定义的属性“fromJS”
- java - 尝试比较现有 Java 项目从 Ant 构建到 Maven 或 Gradle 的迁移?
- python - 如何添加字符串,然后是变量,然后再次添加字符串?
- javascript - 如何循环我的问题?Javascript猜数字游戏