使用Swift强制NSLocalizedString使用特定语言 [英] Force NSLocalizedString to use a specific language using Swift

查看:69
本文介绍了使用Swift强制NSLocalizedString使用特定语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速地,如何强制我的应用从特定的Localizable.strings中读取数据.

With swift, how can I force my app to read data from a specific Localizable.strings.

在实例化ViewController之前,我将其放在didFinishLaunchingWithOptions中,但它仍向我显示英文应用程序.

I put this in didFinishLaunchingWithOptions before instantiate the ViewController but it still show me the App in English.

NSUserDefaults.standardUserDefaults().removeObjectForKey("AppleLanguages")
NSUserDefaults.standardUserDefaults().setObject("fr", forKey: "AppleLanguages"   
NSUserDefaults.standardUserDefaults().synchronize()

我试图像这样为"AppleLanguages"键传递一个数组,但是它仍然不起作用:

And I tried to pass an Array for the "AppleLanguages" key like this but it still doesn't work:

NSUserDefaults.standardUserDefaults().setObject(["fr"], forKey: "AppleLanguages"

完成此操作后,我可以在应用程序内部调用此代码并考虑更改而无需重新启动应用程序吗?

And once this is done, can I call this inside the App and take the changes in consideration without restarting the App?

推荐答案

无法通过更改 AppleLanguages 的值立即更改应用的语言.更改生效之前,需要重新启动应用程序.

It's not possible to change app's language immediately by changing the value of AppleLanguages. It requires restarting the app before the change takes effect.

似乎您的问题是访问不同语言的本地化字符串,而不是更改应用程序的语言,对吗?如果您希望您的应用程序支持多种语言,则只需提供翻译并依靠settings.app进行实际更改即可.

It seems that your problem is accessing the localization strings of different languages rather than changing the app's language, right? If you want your app to support multiple languages, you can just provide the translations and rely on settings.app for the actual change.

如果要从当前使用的本地化之外的其他位置访问本地化字符串,则需要访问正确的翻译包.然后只需查询该捆绑包以获得翻译.下面的代码应该可以解决问题.

If you want to access the localization strings from other than currently used localization, you need to get access to the proper translations bundle. And then just query that bundle for the translations. The following piece of code should do the trick.

let language = "en"
let path = Bundle.main.path(forResource: language, ofType: "lproj")
let bundle = Bundle(path: path!)
let string = bundle?.localizedStringForKey("key", value: nil, table: nil)

这篇关于使用Swift强制NSLocalizedString使用特定语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆