1、OC实现语言国际化(NSBundle扩展)
.h文件
#import <Foundation/Foundation.h>
@interface NSBundle (Language)
+ (void)setLanguage:(NSString *)language;
@end
```
.m文件
```
#import <objc/runtime.h>
static const char _bundle = 0;
@interface BundleEx : NSBundle
@end
@implementation BundleEx
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName {
NSBundle *bundle = objc_getAssociatedObject(self, &_bundle);
return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];
}
@end
@implementation NSBundle (Language)
+ (void)setLanguage:(NSString *)language {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
object_setClass([NSBundle mainBundle], [BundleEx class]);
});
objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
```
使用方法:
```
1、在AppDelegate中:
NSString *currentLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
if (currentLanguage) {
[NSBundle setLanguage:currentLanguage];
}
2、选择语言时保存:
[[NSUserDefaults standardUserDefaults] setObject:currentLanguage forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
[NSBundle setLanguage:currentLanguage];
3、在需要国际化的地方使用 NSLocalizedString(key, @"");
4、重新设置Root
```
2、Swift实现语言国际化
######1、Bundle扩展
```
/**
* 当调用onLanguage后替换掉mainBundle为当前语言的bundle
*/
class BundleEx: Bundle {
override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
if let bundle = languageBundle() {
return bundle.localizedString(forKey: key, value: value, table: tableName)
} else {
return super.localizedString(forKey: key, value: value, table: tableName)
}
}
}
extension Bundle {
//代替dispatch_once
private static var onLanguageDispatchOnce: ()->Void = {
object_setClass(Bundle.main, BundleEx.self)
}
func onLanguage() {
//替换NSBundle.mainBundle()的class为自定义的BundleEx,这样一来我们就可以重写方法
Bundle.onLanguageDispatchOnce()
}
//当前语言的bundle
func languageBundle() -> Bundle? {
return Languager.standardLanguager().currentLanguageBundle
}
}
```
######2、添加Languager类
```
private let kUserLanguage = "AppleLanguages"
/**
* 国际化工具
*/
class Languager: NSObject {
private static var __once: () = {
Static.staticInstance = Languager()
}()
fileprivate struct Static {
static var onceToken : Int = 0
static var staticInstance : Languager? = nil
}
// 单例
class func standardLanguager()->Languager{
_ = Languager.__once
return Static.staticInstance!
}
fileprivate var _currentLanguage:String?
override init() {
super.init()
self.initLanguages()
}
//当前语言Bundle
internal var currentLanguageBundle:Bundle?
// 当前语言获取与切换
var currentLanguage:String {
get{
if(self._currentLanguage==nil){
self._currentLanguage = (UserDefaults.standard.value(forKey: kUserLanguage) as! Array<String>)[0]
}
return self._currentLanguage!
}
set(newLanguage){
if(self._currentLanguage == newLanguage){
return
}
if let path = Bundle.main.path(forResource: newLanguage, ofType: "lproj" ),let bundel = Bundle(path:path){
self.currentLanguageBundle = bundel
self._currentLanguage = newLanguage
}else{
//如果不支持当前语言则加载info中Localization native development region中的值的lporj
let defaultLanguage = (Bundle.main.infoDictionary! as NSDictionary).value(forKey: kCFBundleDevelopmentRegionKey as String) as! String
self.currentLanguageBundle = Bundle(path:Bundle.main.path(forResource: defaultLanguage, ofType: "lproj" )!)
self._currentLanguage = defaultLanguage
}
let def = UserDefaults.standard
def.setValue([self._currentLanguage!], forKey:kUserLanguage)
def.synchronize()
Bundle.main.onLanguage()
}
}
//初始化
func initLanguages(){
let language = (UserDefaults.standard.object(forKey: kUserLanguage) as! Array<String>)[0]
if let path = Bundle.main.path(forResource: language, ofType: "lproj" ),let bundel = Bundle(path:path) {
self.currentLanguageBundle = bundel
self._currentLanguage = language
} else {
//如果不支持当前语言则加载info中Localization native development region中的值的lporj,设置为当前语言
self.currentLanguage = (Bundle.main.infoDictionary! as NSDictionary).value(forKey: kCFBundleDevelopmentRegionKey as String) as! String
print("Languager:\(language)不支持,切换成默认语言\(self._currentLanguage!)")
}
}
/**
获取当前语言的string
*/
func string(_ key:String) -> String {
if let str = self.currentLanguageBundle?.localizedString(forKey: key, value: nil, table: nil){
return str
}
return key
}
}
func localized(_ key:String) -> String {
return Languager.standardLanguager().string(key)
}
```
使用方法:
```
Languager.standardLanguager().currentLanguage = currentLanguages
在需要国际化的地方使用 localized(key)
```
注意:新建String File时,文件名一定要是Localizable,否则无效!
![Snip20170721_1.png](http://upload-images.jianshu.io/upload_images/2107724-5b75ba103e56daff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)