实现过程
- 项目中建立存放国际化文件的bundle,bundle里面包含各种语言的string文件。
2.建立存放国际化key的常量文件。
3.获取系统的语言首选项
NSString *language = [NSLocale preferredLanguages].firstObject;
,再通过
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:bundle ofType:@"bundle"];
languageBundle = [NSBundle bundleWithPath:[[NSBundle bundleWithPath:bundlePath] pathForResource:language ofType:@"lproj"]];
拿到对应语言的bundle,最后通过
NSString *vv = [languageBundle localizedStringForKey:self value:value table:table];
```获取到string里面对应key的字符串。
4.通过给NSString添加分类达到使用点语言获取到对应的字符串。
` [M1905TipView showMessage:kChairIsEndError.value];`
### 分类文件
1.NSString+Localizable.h
import <Foundation/Foundation.h>
//语言bundle文件名字
static NSString *const defaultBundle = @"Bizaia";
@interface NSString (Localizable)
@property (nonatomic, strong ,readonly) NSString *value;
- (NSString *)valueByBundleName:(NSString *)bundle;
- (NSString *)valueByBundleName:(NSString *)bundle language:(NSString *)language defaultValue:(NSString *)value;
- (NSString *)valueByBundleName:(NSString *)bundle language:(NSString *)language defaultValue:(NSString *)value table:(NSString *)table;
@end
2.NSString+Localizable.m
import "NSString+Localizable.h"
static NSMutableDictionary *bundleDic = nil;
static NSString *language = nil;
FOUNDATION_STATIC_INLINE NSString *getLanguage(){
if (language) {
return language;
}
NSString *language = [NSLocale preferredLanguages].firstObject;
if ([language hasPrefix:@"en"]) {
language = @"en";
} else if ([language hasPrefix:@"zh"]) {
language = @"zh-Hans";
} else if([language hasPrefix:@"ja"]){
language = @"ja";
}else {
language = @"zh-Hans";
}
return language;
}
@implementation NSString (Localizable)
- (void)load{
if (!bundleDic) {
bundleDic = [NSMutableDictionary dictionary];
}
if (!language) {
language = getLanguage();
}
}
(NSString *)value{
return [self valueByBundleName:defaultBundle];
}(NSString *)valueByBundleName:(NSString *)bundle{
return [self valueByBundleName:defaultBundle language:language defaultValue:nil];
}(NSString *)valueByBundleName:(NSString *)bundle language:(NSString *)language defaultValue:(NSString *)value{
return [self valueByBundleName:bundle language:language defaultValue:value table:nil];
}(NSString *)valueByBundleName:(NSString *)bundle language:(NSString *)language defaultValue:(NSString *)value table:(NSString *)table{
if (!bundle) {
return [[NSBundle mainBundle] localizedStringForKey:self value:value table:nil];
}
NSBundle *languageBundle = nil;
if (!bundleDic[bundle]) {
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:bundle ofType:@"bundle"];
languageBundle = [NSBundle bundleWithPath:[[NSBundle bundleWithPath:bundlePath] pathForResource:language ofType:@"lproj"]];
bundleDic[bundle] = languageBundle;
}else{
languageBundle = bundleDic[bundle];
}
NSString *vv = [languageBundle localizedStringForKey:self value:value table:table];
return [[NSBundle mainBundle] localizedStringForKey:self value:vv table:table];
}
@end