ios - 在 Swift 3 中设置语言

标签 ios swift swift3

Swift 2 包含函数:

NSBundle.setLanguage("...")

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

最佳答案

setLanguage() 似乎已在 Swift 3 Bundle 中弃用,或者您正在使用 NSBundle 扩展。相反,您可以执行以下操作:

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

let bundle = Bundle(path: path!)

然后您可以使用该 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;
    }
}

用法

"any string from the strings file".localized("en")    // or "sv" for Swedish or "fi" for Finnish

关于ios - 在 Swift 3 中设置语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42806058/

相关文章:

ios - 如何在Swift 3中绘制LineChartData?

ios - 插入我的 UITabBarController 时 View Controller 隐藏的选项卡栏

ios - 运行IOS错误 "failed to read asset tags"xcode 10.13

ios - Swift 表格 View 单元格选择更改复选框图像

swift - 定制信用卡到期日期字段

iOS Swift标签栏 Controller 以编程方式添加项目(新标签)

ios - UIEdgeInsetsMake 是如何工作的?

ios - 使用 NSTimer 连续向上移动 UIViews 看起来不稳定/不流畅

ios - 在 VC 之间切换时 .reloadData () 的问题

ios - SDWeb图像刷新