App要国际推广,需要支持多语言。可以通过本地化语言和切换来实现。本工程可以不切换系统语言,不重启应用直接切换自定义语言。现在只写中英文,其他语言也是同样处理方法。如果支持语言多,切换时间也不会花长时间,瞬间成功切换。
1.创建工程项目
2.配置项目本地化支持简体中文和英文
工程-PROJECT-info->Localizations,点“+”,选择(Chinese(Simplified))添加简体中文,英文Xcode自带有(English),所以不需要再次添加。
3.添加多语言文件
1>.我们选择使用自己的语言文件,所以要创建一个后缀为.strings文件;
2>.需要可以手动切换语言,而不是根据系统语言变换,所以命名不能为Localizable.strings;
3>.文件取名为Language.strings(自己随意命名,后缀为:.strings)(记得Targets要勾选项目)。
4.配置Language.strings本地化,支持简体中文和英文。
1>.选中Language.strings文件,查看Xcode右侧边栏信息;
2>.点击Localization中的Localize…按钮;
3>.选择Base或中文或英文 然后Localize;
4>.勾选中文和英文,Base项可有可无,都选择UseFile。
这时候Language.strings会多出两个子文件,分别对应英文和简体中文。
在项目工程文件夹中也会看到两个文件夹en.lproj和zh-Hans.lproj。
这两个文件夹不要复制其他项目的,因为这两个文件跟本项目工程文件相关联,直接复制过来会读取不到里面的.strings文件。当然,直接复制里面的内容是可以的。
5.在Language.strings添加并完善所有需要转换的文字
1.每个字段都以分号间隔,因为不是OC文件所以不需要使用@表示字符串;
2.“key键”=“value值”,键可以用中文,也可有用英文,性能有没差别看不出。
</pre><pre name="code" class="objc">//English "top" = "top"; "middle" = "middle"; "bottom" = "bottom"; "left" = "left"; "right" = "right"; "enter" = "enter"; "cancel" = "cancel"; "language" = "English"; "back" = "back"; "change" = "change language";
//简体中文 "top" = "上部"; "middle" = "中间"; "bottom" = "底部"; "left" = "左侧"; "right" = "右侧"; "enter" = "确定"; "cancel" = "取消"; "language" = "中文"; "back" = "返回"; "change" = "修改语言";
6.写个PCH宏定义
用来读取语言文件和返回的value值。毕竟在一个项目里会有多个文件会用到,所以用PCH
建立PCH,在Targets -- Build Settings -- Apple LLVM Language -- PrefixHeader 右侧双击 填入工程名/PCH文件名(如:iOS多语言本地化和切换/PrefixHeader.pch)
在pch中输入
/* 获取当前保存在NSUserDefaults的本地语言 #define currentLanguage [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"appLanguage"]] 根据获取语言文件所在路径 文件名类型Type为lproj,即.lproj的文件夹. zh-Hans.lproj和en.loproj 存在NSUserDefaults的适合,中英文就分别设置zh-Hans和en,不可改变。 #define LanguagePath [[NSBundle mainBundle] pathForResource:currentLanguage ofType:@"lproj"] 根据键值获取返回转换结果 Language为语言文件名Language.string #define Localized(key) [[NSBundle bundleWithPath:LanguagePath] localizedStringForKey:(key) value:nil table:@"Language"] */ //等同于上面定义的三个宏综合 #define Localized(key) [[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"]] ofType:@"lproj"]] localizedStringForKey:(key) value:nil table:@"Language"]//<span style="font-family: Arial, Helvetica, sans-serif;">Language一定要和创建的strings文件名相同</span>
注意:
7.保存当前使用语言到NSUserDefaults (添加刷新页面方法)
1>.在 AppDelegate.h声明一个刷新页面的方法,内部实现如图
2>.在AppDelegate.m文件didFinishLaunchingWithOptions获取当前手机语言,并存储到NSUserDefaults。
#import "AppDelegate.h" #import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //添加nav [self mainVC]; //获取当前手机语言,存储到NSUserDefaults。 if (![[NSUserDefaults standardUserDefaults]objectForKey:@"appLanguage"]) { NSArray *languages = [NSLocale preferredLanguages]; NSString *language = [languages objectAtIndex:0]; if ([language hasPrefix:@"zh-Hans"]) {//开头匹配 [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hans" forKey:@"appLanguage"]; }else{ [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:@"appLanguage"]; } } return YES; } //在.h里声明一下 - (void)mainVC { UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:[ViewController new]]; self.window.rootViewController = nav; }
8.创建并初始化UI控件
1>.在ViewController.m创建并初始化UILabel用于显示多语言文字,UIButton切换语言按钮及响应事件。
读取根据语言文件键值获取返回值,使用方法:Localized(key)。 2>.跳转页面实现改变语言
#import "ViewController.h" #import "SecondViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 200)]; lable.backgroundColor = [UIColor groupTableViewBackgroundColor]; lable.text = [NSString stringWithFormat:@"%@ ------ %@",Localized(@"top"),Localized(@"bottom")]; lable.textColor = [UIColor blackColor]; lable.textAlignment = NSTextAlignmentCenter; [self.view addSubview:lable]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(0, CGRectGetMaxY(lable.frame)+100, self.view.frame.size.width, 200); btn.backgroundColor = [UIColor lightGrayColor]; [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [btn setTitle:[NSString stringWithFormat:@"%@",Localized(@"change")] forState:UIControlStateNormal]; [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } -(void)btnClick { [self.navigationController pushViewController:[SecondViewController new] animated:YES]; }
9.添加通知中心(在第二个页面)
1.因为是要刷新所有试图,所以之前的所有试图都要重新初始化,需要重新设置window.rootViewController
2. 为了不再重复代码,就直接调用AppDelegate的toMain方法,来设rootViewController
接收到通知的时候响应事件,也可用不用通知做,直接在按钮点击事件添加语言切换操作。
#import "SecondViewController.h" #import "AppDelegate.h" #define LanguageChanged @"LANGUAGE_CHANGE_NOTIFICATION" @interface SecondViewController () @end @implementation SecondViewController - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; //添加通知中心,监听语言改变 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(languageChanged) name:LanguageChanged object:nil]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; //移除通知中心 [[NSNotificationCenter defaultCenter] removeObserver:self name:LanguageChanged object:nil]; } //KVO跳转 - (void)languageChanged { AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; [appDelegate mainVC]; }
10.添加切换语言事件
UIButton切换语言按钮及响应事件。
//修改本地获取的语言文件-交替
- (void)viewDidLoad { [super viewDidLoad]; self.title = Localized(@"middle"); UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:Localized(@"back") style:UIBarButtonItemStylePlain target:self action:@selector(back)]; self.navigationItem.leftBarButtonItem = left; UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(0, 100, 375, 200); btn.backgroundColor = [UIColor lightGrayColor]; [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [btn setTitle:[NSString stringWithFormat:@"%@",Localized(@"language")] forState:UIControlStateNormal]; [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } - (void)back { [self.navigationController popToRootViewControllerAnimated:YES]; } - (void)btnClick { UIAlertController *alert =[UIAlertController alertControllerWithTitle:Localized(@"chenge") message:nil preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *left = [UIAlertAction actionWithTitle:Localized(@"cancel") style:UIAlertActionStyleCancel handler:nil]; UIAlertAction *right = [UIAlertAction actionWithTitle:Localized(@"enter") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self enterClick]; }]; [alert addAction:left]; [alert addAction:right]; [self presentViewController:alert animated:YES completion:nil]; } - (void)enterClick { //修改本地获取的语言文件--交替 NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"appLanguage"]; if ([language isEqualToString: @"en"]) { [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hans" forKey:@"appLanguage"]; }else { [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:@"appLanguage"]; } [[NSUserDefaults standardUserDefaults] synchronize]; [[NSNotificationCenter defaultCenter] postNotificationName:LanguageChanged object:nil]; }
本文Demo : http://download.csdn.net/detail/jackjia2015/9411833