如何更改xliff导入文件IOS按钮上的语言

时间:2017-01-25 06:03:28

标签: ios localization

因为我有三种语言的西班牙语,意大利语和葡萄牙语的XLIFF文件,它有这样的路径......

enter image description here 我正在使用此代码更改语言

@interface Language : NSObject
+(void)setLanguage:(NSString *)language;
+(NSString *)get:(NSString *)key alter:(NSString *)alternate;
@end

并在实施中

#import "Language.h"
static NSBundle *bundle = nil;

@implementation Language

+(void)initialize {

     NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
     NSArray* languages = [defs objectForKey:@"AppleLanguages"];
     NSString *current = [languages objectAtIndex:0];
    [self setLanguage:current];
}

 /*
  example calls:
 [Language setLanguage:@"it"];
 [Language setLanguage:@"de"];
 */ 
+(void)setLanguage:(NSString *)language {
     NSLog(@"preferredLang: %@",language);
     NSString *path = [[ NSBundle mainBundle]pathForResource:language ofType:@"lproj"];
      bundle = [NSBundle bundleWithPath:path];
 }

 +(NSString *)get:(NSString *)key alter:(NSString *)alternate {
     return [bundle localizedStringForKey:key value:alternate table:nil];
 }

 @end

按下按钮,我就是这样......

-(IBAction)changeLanguage:(Id)sender {
   [Language setLanguage:@"it"];
}

但它不能在runntime或之后改变语言。请帮助

1 个答案:

答案 0 :(得分:2)

我使用此代码根据所选语言更改文本,当点击按钮仅根据选择语言设置“CurrentLanguage”标记值时。整个应用转换选定的语言。

+(NSString *)getTextAsLanguage : (NSString *)strKey
{
    NSString *path1;
    NSString *strCurrentLanguage = [[NSUserDefaults standardUserDefaults] valueForKey:@"CurrentLanguage"];

    if ([strCurrentLanguage  isEqualToString:@"en"])
        path1 = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
    else if ([strCurrentLanguage  isEqual: @"ch"])
        path1 = [[NSBundle mainBundle] pathForResource:@"zh" ofType:@"lproj"];

    strKey = [strKey stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSBundle *languageBundle = [NSBundle bundleWithPath:path1];
    NSString *str = [languageBundle localizedStringForKey:strKey value:@"" table:nil];
    return str;
}

点击此代码使用的按钮:

- (IBAction)btnLanguageEnlgishChangeClicked:(id)sender
{
    [[NSUserDefaults standardUserDefaults] setValue:@"en" forKey:@"CurrentLanguage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

希望对你有所帮助。