【问题标题】:iPad App - Change languages programmaticallyiPad App - 以编程方式更改语言
【发布时间】:2012-08-27 18:15:39
【问题描述】:

我的应用需要两种语言,英语和法语。

我已经在它们各自的“en.lproj”和“fr.lproj”文件夹中设置了 Localizable.strings 文件......当我更改 iPad 的语言(在本机设置应用程序中)时,然后启动我的应用程序,它实际上确实加载了正确的文本(即英文副本或法文副本)。

我需要在两种语言之间进行 UISegmentedControl 切换,而无需重新启动应用程序。

如何让应用程序更改(当前)语言,以便当我调用(重新)设置所有 UILabel 的文本和 UIImageViews 的图像的方法时,它们从对面的 .lproj 文件夹的可本地化中读取。字符串文件?!?

我知道如何使用 UISegmentedControl,这不是我的问题。我正在寻找更多设置应用程序的捆绑语言或区域设置或其他东西的代码行(因为我对国际化.本地化很陌生)。

-

我如何为 UIImageView 设置图像的示例:

myUIImageView1.image = [UIImage imageNamed:NSLocalizedString(@"myUIImageView1", @"comment for the translator")];

我如何设置 UILabel 文本的示例:

myLabel1.text = NSLocalizedString(@"myLabel1", @"comment for the translator");

【问题讨论】:

标签: iphone objective-c ios ipad localization


【解决方案1】:

找到解决方案!!!

以下测试应用程序具有从正确的“Localizable.strings”文件中读取所需字符串的函数(基于选择的语言): https://github.com/object2dot0/Advance-Localization-in-ios-apps

-

我把这段代码和设置应用程序主要语言所需的代码(在 Brayden 发布的上述答案中找到: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"];
    }

-

感谢大家的帮助!!!

-克里斯·阿林森

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2018-08-09
    相关资源
    最近更新 更多