iOS Change app Language doesn't take effect

孤人 提交于 2019-12-12 01:05:14

问题


I am changing my iOS application preferred language dynamically using this setting:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"ar"] forKey:@"AppleLanguages"];

Then I load a localised resource file from the main NSBundle object, but the loaded file isn't of the new language, it's loaded in the default english language until I restart the application totally then it loads the arabic localisation.

I want to force NSBundle to load the resource file in the new language @"ar" not the language been set when app starts. How?


回答1:


Your method is a hacky way to get what you need, and requires app restart to take effect.

It is best to use NSLocalizedStringFromTableInBundle instead of NSLocalizedString, and provide the bundle for that language.

NSString* path = [[NSBundle mainBundle] pathForResource:@"ar" ofType:@"lproj"];
NSBundle* ar_bundle = [NSBundle bundleWithPath:path];

NSLocalizedStringFromTableInBundle(@"str", nil, ar_bundle, @"comment");

If you put the bundle in a global scope, you can create a macro for ease:

#define ARLocalizedString(str, cmt) NSLocalizedStringFromTableInBundle(str, nil, ar_bundle, cmt)



回答2:


I have tried this and its working fine without restarting the app:

//Use this in constants
#ifdef NSLocalizedString
#undef NSLocalizedString
#endif
#define NSLocalizedString(str, cmt) NSLocalizedStringFromTableInBundle(str, nil, newLangbundle, cmt)

newLangbundle --> Define a global variable in .pch and vary it according to language selection using this,

 NSString* path = [[NSBundle mainBundle] pathForResource:@"th" ofType:@"lproj"];
 newLangbundle = [NSBundle bundleWithPath:path];



回答3:


You need to synchronize user defaults after changing the language: [[NSUserDefaults standardUserDefaults] default synchronize]



来源:https://stackoverflow.com/questions/20818284/ios-change-app-language-doesnt-take-effect

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