Overriding preferred strings localization on the fly for testing

夙愿已清 提交于 2019-12-03 03:51:37
Ben Zotto

The only way to do this that I've figured out is by using the subtle trick suggested by this answer. You can wrap NSLocalizedString() in a function that knows about a localization "override", and chooses how to get its strings based on whether that is set. When you want to override, you can create a "sub bundle" from the localization's directory, and then pull string from that bundle. Here's the gist of it:

if (CurrentLocalization != nil) {
    NSBundle * locBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:CurrentLocalization ofType:@"lproj"]];
    return [locBundle localizedStringForKey:key value:nil table:nil];
} else {
    return NSLocalizedString(key, @"");
}    

etc.

The trick to use specific language by selecting it from the app is to force the NSLocalizedString to use specific bundle depending on the selected language ,

here is the post i have written for this http://learning-ios.blogspot.com/2011/04/advance-localization-in-ios-apps.html

and here is the code of one sample app https://github.com/object2dot0/Advance-Localization-in-ios-apps

Set the AppleLanguages default to an array consisting of the preferred languages, most preferential first. For example if you only care about English, set it to '("en");'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!