iOS 多语言

读取多语言的宏方法是:

NSLocalizedString(key, comment)

对应的是:

[NSBundle.mainBundle localizedStringForKey:(key) value:@"" table:nil]

所以,若要在应用内显示特定的语言,需要先使mainBundle对象读取相应的语言配置,比如:

NSString * hansBundlePath = [[NSBundle mainBundle] pathForResource:@"zh-Hans" ofType:@"lproj"]; // 加载简体中文的配置
NSBundle * hansBundle = [NSBundle bundleWithPath:hansBundlePath];

为了方便,可以利用category技术在load方法中,通过object_setClass替换系统方法mainBundle,使其在特定条件下加载特定的语言配置。

+ (void)load {
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
     object_setClass([NSBundle mainBundle], [LanguageBundle class]);
  });

}

LanguageBundle的定义可以是下面这样:

@interface LanguageBundle : NSBundle

@end

static NSBundle * enBundle;
static NSBundle * hansBundle;

@implementation LanguageBundle

- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName {
    if ([LanguageBundle cl_mainBundle]) {
        return [[LanguageBundle cl_mainBundle] localizedStringForKey:key value:value table:tableName]
        ;
    } else {
        return [super localizedStringForKey:key value:value table:tableName];
    }
}

+ (NSBundle *)cl_mainBundle {
    if (/** 判断条件,比如,用户设置过显示中文 */) {
            if (!hansBundle) {
                NSString * hansBundlePath = [[NSBundle mainBundle] pathForResource:@"zh-Hans" ofType:@"lproj"];
                hansBundle = [NSBundle bundleWithPath:hansBundlePath];
            }
            return hansBundle;
     } else {
            if (!enBundle) {
                NSString * enBundlePath = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
                enBundle = [NSBundle bundleWithPath:enBundlePath];
            }
            return enBundle;
     }
}

@end

另外,判断当前系统语言,这个不代表APP内显示的语言。

如下:

NSArray * appLanguages = [NSLocale preferredLanguages];
//判断第一个
if ([[appLanguages firstObject] hasPrefix:@"zh-Han"]) {
     // 简体中文
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值