在Swift 3中设置语言

Kir*_*ill 0 ios swift swift3

Swift 2包含功能:

NSBundle.setLanguage("...")
Run Code Online (Sandbox Code Playgroud)

但新类"Bundle"在Swift 3中不包含方法setLanguage.在Swift 3中设置语言的最佳方法是什么?

Thu*_*uct 5

setLanguage()似乎已在Swift 3中弃用Bundle或您正在使用NSBundle扩展程序.相反,这是你可以做的:

let path = Bundle.main.path(forResource: lang, ofType: "lproj")

let bundle = Bundle(path: path!)
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用它bundle来获取本地化的字符串.这是我为此写的扩展:

extension String {
    func localized(lang:String) -> String? {
        if let path = Bundle.main.path(forResource: lang, ofType: "lproj") {
            if let bundle = Bundle(path: path) {
                return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
            }
        }

        return nil;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

"any string from the strings file".localized("en")    // or "sv" for Swedish or "fi" for Finnish
Run Code Online (Sandbox Code Playgroud)

  • 我建议不要在你的快速代码中使用强制解包(路径!和捆绑!),一个警卫或者if会做出这个工作并让你免于崩溃. (2认同)