ios 应用多语言自由切换实现
第一次进入应用获取本机语言.1.如果本机语言在软件实现语言列表里.则默认选中本机语言,但是用户还是可以选择其它语言.2.如果本机语言不在软件实现语言列表里,则默认选中英语.用户还是可以选择其它语言.
所有要更换语言的controller里注册通知.当用户选择了一个语言后发送语言修改的通知.控制器收到语言修改通知后,对需要修改语言的控制进行重新设置.
/** 初始化语言 */
- (void)initLanguage{
//1. 获取系统支持的语言
_languages = [NSMutableArrayarrayWithCapacity:5];
NSURL *url = [[NSBundlemainBundle] URLForResource:kLanguagePlistwithExtension:kTypePlist];
NSDictionary *dic = [NSDictionarydictionaryWithContentsOfURL:url];
//2 生成语言对象
[dicenumerateKeysAndObjectsUsingBlock:^(id key,id obj, BOOL *stop) {
DYCXLanguage *language = [DYCXLanguagelanguageWithKey:key AndValue:obj];
[_languagesaddObject:language];
}];
//3. 获取用户保存的语言[0] = 简体中文, [1] = zh-Hans;
NSString *userLanguageValue = [selfgetUserLanguage];
if (!userLanguageValue) {
userLanguageValue =kDefaultUserLanguage;
//3.1 获取系统语言
NSString * localLanguage = [selfgetLocalLanguageValue];
//3.2. 确定默认语言
for (DYCXLanguage *languagein _languages) {
//3.3.如果软件语言包涵系统语言默认为系统语言,如果不包涵默认设置为英语
if ([localLanguage isEqualToString:language.languageValue]) {
userLanguageValue = localLanguage;
}
}
}
//4. 设置当前语言
for (DYCXLanguage *languagein _languages) {
if ([userLanguageValue isEqualToString:language.languageValue]) {
language.used =YES;
_userLanguage = language;
break;
}
}
}
- (NSString *)getLocalLanguageValue{
NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
return [languages objectAtIndex:0];
}
#pragma mark - 语言更改,重新加载
- (void)reloadStringWithLanguage{
[_confirm setTitle:[NSString localizedWithString:@"dialog_positive_key"] forState:UIControlStateNormal];
_selectLanguage.text = [NSString localizedWithString:@"select_language_key"];
if ([self.delegate respondsToSelector:@selector(onLanguageChange)]) {
[self.delegate onLanguageChange];
}
}
#pragma mark - NSString 的分类,加载对应目录里的string
+ (NSString *)localizedWithString:(NSString *)key{
NSString *area = [DYCXConfig sharedDYCXConfig].userLanguage.languageValue;
if (!area) {
area = kDefaultUserLanguage;
}
NSString *table = [NSString stringWithFormat:@"%@.lproj/Localizable", area];
NSString *localizedString = [[NSBundle mainBundle] localizedStringForKey:(key) value:nil table:(table)];
NSAssert(localizedString, @"localized error, table = %@, key = %@", table, key);
return localizedString;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。