我有一个需要两种语言的应用程序:英语和法语。
我已经在各自的“en.lproj”和“fr.lproj”文件夹中设置了 Localized.strings 文件...当我更改 iPad 的语言(在本机设置应用程序中),然后启动我的应用程序时,它确实如此事实上加载正确的文本(即英文副本或法文副本)。
我需要在两种语言之间进行 UISegmentedControl 切换,而无需重新启动应用程序。
如何让应用程序更改(当前)语言,以便当我调用(重新)设置所有 UILabels 文本和 UIImageViews 图像的方法时,它们从相反的 .lproj 文件夹的 Localized.strings 文件中读取?!?
我知道如何使用 UISegmentedControl,这不是我的问题。我正在寻找更多设置应用程序的捆绑语言或区域设置或其他内容的代码行(因为我对 Internationalization.localization 还很陌生)。
-
我如何为 UIImageView 设置图像的示例:
myUIImageView1.image = [UIImage imageNamed:NSLocalizedString(@"myUIImageView1", @"comment for the translator")];
我如何设置 UILabel 文本的示例:
myLabel1.text = NSLocalizedString(@"myLabel1", @"comment for the translator");
找到解决方案!
以下测试应用程序有一个函数,可以从正确的“Localized.strings”文件中读取所需的字符串(基于所选的语言):https://github.com/object2dot0/Advance-Localization-in-ios-apps https://github.com/object2dot0/Advance-Localization-in-ios-apps
-
我获取了此代码以及设置应用程序的主要语言所需的代码(在 Brayden 发布的上述答案中找到:如何强制 NSLocalizedString 使用特定语言 https://stackoverflow.com/questions/1669645/how-to-force-nslocalizedstring-to-use-a-specific-language),并将它们放在一起。
这是我的代码现在的样子(注意 - 我的 UISegmentedControl 在其视图的 viewController 中调用一个函数 [当触发 UISegmentedControl 的“值更改”方法时],然后调用父 viewController 中的toggleLanguage 函数):
-(void)toggleLanguage:(NSString *)primaryLanguage secondaryLanguage:(NSString *)secondaryLanguage
{
//set app's primary language
defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSArray arrayWithObjects:primaryLanguage,secondaryLanguage,nil] forKey:@"AppleLanguages"];
[defaults synchronize];
//update UILabel and UIImageViews
[self setLanguageSpecificItems];
}
-(NSString *)languageSelectedStringForKey:(NSString *)key
{
//read primary language
NSArray *appleLanguagesArray = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [appleLanguagesArray objectAtIndex:0];
//get the path to the desired lproj file
NSString *path;
if(currentLanguage==@"en")
{
path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
}
else
if(currentLanguage==@"fr")
{
path = [[NSBundle mainBundle] pathForResource:@"fr" ofType:@"lproj"];
}
NSBundle* languageBundle = [NSBundle bundleWithPath:path];
//find and return the desired string
NSString* str=[languageBundle localizedStringForKey:key value:@"" table:nil];
return str;
}
-(void)setLanguageSpecificItems
{
myUIImageView1.image = [UIImage imageNamed:[self languageSelectedStringForKey:@"myUIImageView1"]];
myLabel1.text = [self languageSelectedStringForKey:@"myLabel1"];
}
-
谢谢大家的帮助!!!
——克里斯·阿林森
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)