随着时代的发展,应用程序相继出现了不同语言的版本方案,中文,英文,法文,韩文等等;想在应用程序中实现语言的自由切换,需要配置多个语言的文件,根据用户的动态选择获取不同语言文件下的语言文件,从而显示到界面上面。这里先说中英文的切换,至于其他语言操作复制即可!!!
1.新建工程之类的就不用说了,配置项目本地化支持简体中文和英文
工程-PROJECT-info->Localizations,点“+”,选择(Chinese(Simplified))添加简体中文,英文Xcode自带有(English),所以不需要再次添加。(点击添加弹出语言菜单,即可选择你所需要的语言)
2.现在可以添加多语言文件了。
注意:需要手动切换语言,而不是根据系统语言变换,所以命名不能与系统语言文件同名,即Localizable.strings;
自己随意命名,后缀是.strings,一定要记得Targets要勾选项目
3.配置English.strings本地化,现在支持中文和英文。
(1)选中English.strings文件,查看右边栏中的信息;(2)点击Localization中的按钮,弹出框中显示出前面添加的语言;(3)选择中文和英文,base选项可有可无,
勾选之后,English.strings中多出了两个文件
完成之后便是完成了项目内多语言环境的配置,下面看一下这两个文件中应该怎样写
4.文件中添加两个需要的字符串
中文:
"change_language" = "悄悄是别离的笙箫,沉默是今晚的康桥";
"button" = "切换语言";
英文:
"change_language" = "Quietness is my farewell music, silence is Cambridge tonight";
"button" = "Change Language";
5.配置环境已经完成,现在看看代码怎么写
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSString *currLanguage = [def valueForKey:@"LocalLanguageKey"];
if(!currLanguage){
NSArray *preferredLanguages = [NSLocale preferredLanguages];
currLanguage = preferredLanguages[0];
if ([currLanguage hasPrefix:@"en"]) {
currLanguage = @"en";
}else if ([currLanguage hasPrefix:@"zh"]) {
currLanguage = @"zh-Hant";
}else currLanguage = @"en";
[def setValue:currLanguage forKey:@"LocalLanguageKey"];
[def synchronize];
}
//废弃按钮
UIButton *btnAbandoned=[UIButton buttonWithType:UIButtonTypeCustom];
btnAbandoned.frame=CGRectMake(100, 100, 100, 45);
[btnAbandoned setBackgroundColor:[UIColor orangeColor]];
[btnAbandoned addTarget:self action:@selector(btnAbandonedClick:) forControlEvents:UIControlEventTouchDown];
[btnAbandoned setTitle:@"点击" forState:UIControlStateNormal];
[btnAbandoned setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btnAbandoned.titleLabel setFont:[UIFont systemFontOfSize:16]];
[self.view addSubview:btnAbandoned];
}
- (void)btnAbandonedClick:(UIButton*)sender{
//修改语言
NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"LocalLanguageKey"];
if ([language isEqualToString:@"en"]) {
[[NSUserDefaults standardUserDefaults] setValue:@"zh-Hant" forKey:@"LocalLanguageKey"];
}else{
[[NSUserDefaults standardUserDefaults] setValue:@"en" forKey:@"LocalLanguageKey"];
}
NSString *path = [[NSBundle mainBundle] pathForResource:[[NSUserDefaults standardUserDefaults] objectForKey:@"LocalLanguageKey"] ofType:@"lproj"];
NSBundle* bundle = [NSBundle bundleWithPath:path];
//此处是上面赋值的bundle
NSString *str = [bundle localizedStringForKey:@"change_language" value:nil table:@"MultiLanguage"];
NSString *buttonStr = [bundle localizedStringForKey:@"button" value:nil table:@"MultiLanguage"];
NSLog(@"wenzi:%@,%@",str,buttonStr);
}