首页 > 解决方案 > 如何在 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()
           
           
    }
}

标签: swiftswiftui

解决方案


见此之前

然后是一个方便的扩展:

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";


推荐阅读