如何使用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设置了常规Localizable.strings(例如en.lproj,de.lproj等),则可以在需要的任何地方使用它:
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屋!