因为我有三种语言的西班牙语,意大利语和葡萄牙语的XLIFF文件,它有这样的路径......
@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或之后改变语言。请帮助
答案 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];
}
希望对你有所帮助。