我对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()
}
}