如何使用 Swift 以编程方式更改语言环境 [英] How can I change locale programmatically with Swift
问题描述
我正在使用 Swift 在 XCODE 6.3 上制作 ios 应用程序.我的应用程序将具有如下图所示的选择语言功能
I am making ios app on XCODE 6.3 by Swift. And my app will have the choose language function like the image below
我已经有本地语言的故事板.但我不知道如何通过按钮以编程方式关闭应用程序的本地化.
I already have storyboard for my local language. But i can't find out how to change the localization programmatically off the app by the button.
谁知道怎么做
推荐答案
这是一种使用 Swift 即时更改它的方法,向 String 添加扩展函数:
Here's a way to change it on the fly with Swift, add an extension function to String:
extension String {
func localized(lang:String) ->String {
let path = NSBundle.mainBundle().pathForResource(lang, ofType: "lproj")
let bundle = NSBundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}}
斯威夫特 4:
extension String {
func localized(_ lang:String) ->String {
let path = Bundle.main.path(forResource: lang, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}}
然后假设您使用 lang_id.lproj(例如 en.lproj、de.lproj 等)设置了常规的 Localizable.strings,您可以在任何需要的地方使用它:
then assuming you have the regular Localizable.strings set up with lang_id.lproj ( e.g. en.lproj, de.lproj etc. ) you can use this anywhere you need:
var val = "MY_LOCALIZED_STRING".localized("de")
这篇关于如何使用 Swift 以编程方式更改语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!