我有一个应用程序需要两种语言,英语和法语。
我已经在各自的“en.lproj”和“fr.lproj”文件夹中设置了 Localizable.strings 文件……当我更改 iPad 的语言时(在 native 设置应用程序中),然后启动我的应用程序,它实际上加载了正确的文本(即英文副本或法文副本)。
我需要一个 UISegmentedControl 在 2 种语言之间切换,而无需重新启动应用程序。
我如何让应用程序更改(当前)语言,以便在我调用一个方法(重新)设置所有 UILabel 的文本和 UIImageView 的图像时,它们从对面的 .lproj 文件夹的 Localizable 中读取。字符串文件?!?
我知道如何使用 UISegmentedControl,这不是我的问题。我正在寻找一行代码来设置应用程序的捆绑语言或语言环境或其他东西(因为我对国际化很陌生。本地化)。
-
我如何为 UIImageView 设置图像的示例:
myUIImageView1.image = [UIImage imageNamed:NSLocalizedString(@"myUIImageView1", @"comment for the translator")];
我如何设置 UILabel 文本的示例:
myLabel1.text = NSLocalizedString(@"myLabel1", @"comment for the translator");
最佳答案
找到解决方案!!!
以下测试应用程序具有从正确的“Localizable.strings”文件(基于所选语言)中读取所需字符串的功能: https://github.com/object2dot0/Advance-Localization-in-ios-apps
-
我把这段代码和设置应用程序主要语言所需的代码(在 Brayden 发布的上述答案中找到:How to force NSLocalizedString to use a specific language)放在一起。
这是我的代码现在的样子(注意 - 我的 UISegmentedControl 在它的 View 的 viewController 中调用一个函数 [当 UISegmentedControl 的“Value Changed”方法被触发时],然后调用父 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"];
}
-
感谢大家的帮助!!!
-克里斯·阿林森
关于iphone - iPad App - 以编程方式更改语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12147291/