这是我的做法。我猜窍门在于使用 NSLocalizedStringFromTableInBundle 而不是 NSLocalizedString。
对于所有的字符串,使用以下方法:
someLabel.text = NSLocalizedStringFromTableInBundle(@"Your String to be localized, %@",nil,self.localeBundle,@"some context for translators");
要更改语言,请运行此代码
NSString * language = @"zh-Hans";
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或其他地方进行检查)
注:本文为IT技术相关内容,涉及代码编写,请谨慎操作。
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"] ];
}