这就是我所做的。我想诀窍是使用 NSLocalizedStringFromTableInBundle 而不是 NSLocalizedString。
对于所有字符串,使用 this
someLabel.text = NSLocalizedStringFromTableInBundle(@"Your String to be localized, %@",nil,self.localeBundle,@"some context for translators");
要更改语言,请运行此代码
NSString * language = @"zh-Hans"; //or whatever language you want
NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
if (path) {
self.localeBundle = [NSBundle bundleWithPath:path];
}
else {
self.localeBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"] ];
}
在此之后,您可能需要调用任何更新代码来将字符串更新为新语言,例如再次运行它
someLabel.text = NSLocalizedStringFromTableInBundle(@"Your String to be localized, %@",nil,self.localeBundle,@"some context for translators");
仅此而已。无需重启应用程序。也与系统设置兼容(如果您通过 iOS 设置设置语言,它也可以工作)。不需要外部库。不需要越狱。它也适用于 genstrings。
当然,您仍应照常执行以使您的应用设置保持不变:
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hans", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
(并检查您的 viewDidLoad 或其他内容)
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
if (path) {
self.localeBundle = [NSBundle bundleWithPath:path];
}
else {
self.localeBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"] ];
}