1七兜、增加多語(yǔ)言環(huán)境
2武翎、創(chuàng)建多語(yǔ)言文件
3法挨、使用多語(yǔ)言文件添加多語(yǔ)言變量
4零院、使用多語(yǔ)言
NSBundle *bundle = [NSBundle mainBundle];
NSString *string = NSLocalizedStringFromTableInBundle(key, @"Localizable",bundle, nil);
對(duì)于有些app存在app內(nèi)語(yǔ)言切換功能莉御,我們可以通過(guò)自定義獲取多語(yǔ)言配置來(lái)進(jìn)行實(shí)現(xiàn)党瓮。
我們創(chuàng)建一個(gè)單獨(dú)的多語(yǔ)言文件管理類(lèi)來(lái)進(jìn)行統(tǒng)一管理萤捆。
//獲取本地語(yǔ)言
#define LocalizedString(key) [[LanguageManager sharedInstance] localizedStringForKey:key]
@interface LanguageManager : NSObject
+ (instancetype)sharedInstance;
- (void)setApplicationLanguageTo:(NSString *)languageCode;
- (NSString *)localizedStringForKey:(NSString *)key;
@end
實(shí)現(xiàn)對(duì)應(yīng)的方法
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];
// 發(fā)送通知讓所有觀察者知道語(yǔ)言已更改
[[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