language change only after restart on iphone

浪子不回头ぞ 提交于 2019-11-27 20:19:26

Update the answer "How to change the languages within the app"

NSLocalizedString() (and variants thereof) access the "AppleLanguages" key in NSUserDefaults to determine what the user's settings for preferred languages are. This returns an array of language codes, with the first one being the one set by the user for their phone, and the subsequent ones used as fallbacks if a resource is not available in the preferred language.

You can override the global setting for your own application if you wish by using the setObject:forKey: method to set your own language list just like you've done it. This will take precedence over the globally set value and be returned to any code in your application that is performing localization. The code for this would look something like:

[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", @"en", @"fr", nil] forKey:@"AppleLanguages"]; 

Note: To be on safe side make sure that you use the appropriate pre-defined languages name.

Below is the code snippet, but you MUST have all localization files in your project.

@implementation LocalizeLanguage

static NSBundle *bundle = nil;

+(void)initialize {
     NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
     NSArray* languages = [defs objectForKey:@"AppleLanguages"];
     NSString *current = [[languages objectAtIndex:0] retain];
     [self setLocalizeLanguage:current];
}

/*
  [LocalizeLanguage setLocalizeLanguage:@"en"];
  [LocalizeLanguage setLocalizeLanguage:@"fr"];
*/

+(void)setLocalizeLanguage:(NSString *)lang {
     NSLog(@"preferredLang: %@", lang);
     NSString *path = [[ NSBundle mainBundle ] pathForResource:lang ofType:@"lproj" ];
     bundle = [[NSBundle bundleWithPath:path] retain];
}

+(NSString *)get:(NSString *)key alter:(NSString *)alternate {
    return [bundle localizedStringForKey:key value:alternate table:nil];
}

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