参考:http://blog.csdn.net/yang8456211/article/details/12031667
1.原理。
查看NSLocalizedString(@"abc",nil);的定义。1 2 | #define NSLocalizedString(key, comment) [[ NSBundle mainBundle] localizedStringForKey:(key) value:@ "" table: nil ] |
然后思考,为什么这个定义会定位到当前系统默认的语言对应的strings文件呢?
如果这点想通了,那问题就迎刃而解了不是?
2.具体解析
重定义NSLocalizedstring。
1 2 3 | #define AppLanguage @"appLanguage" #define CustomLocalizedString(key, comment) [[ NSBundle bundleWithPath:[[ NSBundle mainBundle] pathForResource:[ NSString stringWithFormat:@ "%@" ,[[ NSUserDefaults standardUserDefaults] objectForKey:@ "appLanguage" ]] ofType:@ "lproj" ]] localizedStringForKey:(key) value:@ "" table: nil ] |
不用解释了吧?查找对应的strings文件。
3.用法
1 2 3 4 | if (![[ NSUserDefaults standardUserDefaults]objectForKey:AppLanguage]) { [[ NSUserDefaults standardUserDefaults] setObject:@ "zh-Hans" forKey:AppLanguage]; } label.text= CustomLocalizedString(@ "sub_menu_download" , nil ); //@"离线下载"; |
4.切换
点击中英文切换按钮时,
1 2 3 4 5 6 7 8 | NSString *currentLanguage = [[ NSUserDefaults standardUserDefaults]objectForKey:AppLanguage]; if ([currentLanguage isEqualToString: @ "en" ]) { [[ NSUserDefaults standardUserDefaults] setObject:@ "zh-Hans" forKey:AppLanguage]; } else { [[ NSUserDefaults standardUserDefaults] setObject:@ "en" forKey:AppLanguage]; } [[ NSUserDefaults standardUserDefaults] synchronize]; |
程序还要再做进一步的界面相关的处理,如是tabbar则重新初始化等等