language change only after restart on iphone

半世苍凉 提交于 2019-11-26 20:22:36

问题


I'm trying to change app language, but when I run this code in main.h language chages after I shut down an App and run it again. Is this possible to change language without restarting?

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSArray *languages = [NSArray arrayWithObject:@"en_GB"];
    [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}

回答1:


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


来源:https://stackoverflow.com/questions/5912018/language-change-only-after-restart-on-iphone

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