第一次進入應用獲取本機語言.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;
}