1、增加多语言环境
image.png
2、创建多语言文件
image.png
3、使用多语言文件添加多语言变量
image.png
image.png
4、使用多语言
NSBundle *bundle = [NSBundle mainBundle];
NSString *string = NSLocalizedStringFromTableInBundle(key, @"Localizable",bundle, nil);
对于有些app存在app内语言切换功能,我们可以通过自定义获取多语言配置来进行实现。
我们创建一个单独的多语言文件管理类来进行统一管理。
//获取本地语言
#define LocalizedString(key) [[LanguageManager sharedInstance] localizedStringForKey:key]
@interface LanguageManager : NSObject
+ (instancetype)sharedInstance;
- (void)setApplicationLanguageTo:(NSString *)languageCode;
- (NSString *)localizedStringForKey:(NSString *)key;
@end
实现对应的方法
static NSString *const kUserSelectedLanguageKey = @"UserSelectedLanguage";
static LanguageManager *_sharedInstance = nil;
@implementation LanguageManager
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
- (NSString *)currentLanguage {
NSString *userSelectedLanguage = [[NSUserDefaults standardUserDefaults] stringForKey:kUserSelectedLanguageKey];
if (userSelectedLanguage) {
return userSelectedLanguage;
} else {
NSArray<NSString *> *preferredLanguages = [[NSLocale preferredLanguages] copy];
return [preferredLanguages firstObject];
}
}
- (void)setApplicationLanguageTo:(NSString *)languageCode {
[[NSUserDefaults standardUserDefaults] setObject:languageCode forKey:kUserSelectedLanguageKey];
[[NSUserDefaults standardUserDefaults] synchronize];
// 发送通知让所有观察者知道语言已更改
[[NSNotificationCenter defaultCenter] postNotificationName:@"LanguageDidChangeNotification" object:nil];
}
- (NSBundle *)localizedBundle {
NSString *language = [self currentLanguage];
NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
if (path) {
return [NSBundle bundleWithPath:path];
} else {
return [NSBundle mainBundle];
}
}
- (NSString *)localizedStringForKey:(NSString *)key {
NSBundle *bundle = [self localizedBundle];
NSString *string = NSLocalizedStringFromTableInBundle(key, @"Localizable",bundle, nil);
return string;
}
@end
网友评论