在iPhone上NSLocalizedString返回iPhone语言的字符串。 是否有可能强制NSLocalizedString使用特定语言来拥有应用程序 用不同的语言吗?


当前回答

你可以这样做:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings" inDirectory:nil forLocalization:@"es"];


NSBundle *spanishBundle = [[NSBundle alloc] initWithPath:[bundlePath stringByDeletingLastPathComponent]];

NSLocalizedStringFromTableInBundle(@"House", nil, spanishBundle, nil):

其他回答

这里有一个不错的解决方案,它不需要重新启动应用程序。

https://github.com/cmaftuleac/BundleLocalization

这个实现通过在NSBundle内部进行调整来工作。这个想法是你在NSBundle对象的实例上重写localizedStringForKey方法,然后用不同的语言在不同的bundle上调用这个方法。简单而优雅的完全兼容所有类型的资源。

你可以用你想要做这件事的本地化字符串集构建一个子bundle,然后使用NSLocalizedStringFromTableInBundle()来加载它们。(我假设这是与你可能在应用上做的正常UI本地化分开的内容。)

NSLocalizedString() reads the value for the key AppleLanguages from the standard user defaults ([NSUserDefaults standardUserDefaults]). It uses that value to choose an appropriate localization among all existing localizations at runtime. When Apple builds the user defaults dictionary at app launch, they look up the preferred language(s) key in the system preferences and copy the value from there. This also explains for example why changing the language settings in OS X has no effect on running apps, only on apps started thereafter. Once copied, the value is not updated just because the settings change. That's why iOS restarts all apps if you change then language.

但是,用户默认字典的所有值都可以被命令行参数覆盖。请参阅NSArgumentDomain上的NSUserDefaults文档。这甚至包括那些从应用程序首选项(.plist)文件加载的值。如果您只是为了测试而更改一个值,了解这一点非常有用。

所以如果你想改变语言只是为了测试,你可能不想改变你的代码(如果你忘记删除这段代码…),而是告诉Xcode用一个命令行参数启动你的应用程序(例如使用西班牙语本地化):

根本不需要修改代码。只需为不同的语言创建不同的方案,您可以快速启动应用程序一次在一种语言和一次在另一种只需切换方案。

斯威夫特版本:

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

NSLocalizedString()(及其变体)访问NSUserDefaults中的"AppleLanguages"键,以确定用户的首选语言设置是什么。这将返回一个语言代码数组,第一个是用户为他们的手机设置的代码,如果资源在首选语言中不可用,则后续的代码用作备用。(在桌面上,用户可以在系统首选项中自定义顺序指定多种语言)

如果你愿意,你可以使用setObject:forKey:方法来设置你自己的语言列表,为你自己的应用程序覆盖全局设置。这将优先于全局设置的值,并返回给正在执行本地化的应用程序中的任何代码。它的代码看起来像这样:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", @"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate

这将使德语成为应用程序的首选语言,英语和法语作为备用语言。您可能希望在应用程序启动早期的某个时候调用它。您可以在这里阅读有关语言/区域设置首选项的更多信息:国际化编程主题:获取当前语言和区域设置