ViewController
在设置 > 常规 > 语言与地区 > iPhone 语言
中。显示
- (IBAction)selectLanguageAction:(UIButton *)button {
GSLanguagePickerController *vc = [GSLanguagePickerController new];
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
[self presentViewController:navi animated:YES completion:nil];
}
或者推入
- (IBAction)selectLanguageAction:(UIButton *)button {
GSLanguagePickerController *vc = [GSLanguagePickerController new];
[self.navigationController pushViewController:vc animated:YES];
}
您还可以监听语言变化通知 NSCurrentLocaleDidChangeNotification
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(languageChanged:) name:NSCurrentLocaleDidChangeNotification object:nil];
}
- (void)languageChanged:(NSNotification *)notification {
NSString *languageId = notification.object;
NSLog(@"Language has changed: %@", languageId);
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:[NSBundle defaultLanguage]];
NSString *languageName = [locale displayNameForKey:NSLocaleIdentifier value:languageId];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Language has changed" message:[NSString stringWithFormat:@"%@: %@", languageId, languageName] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:action];
[self presentViewController:alertController animated:YES completion:nil];
// TODO: reload viewcontroller or other works
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
GSLanguagePickerController 需要 iOS 8.0 及以上版本。
GSLanguagePickerController 可通过 CocoaPods 获取。要安装它,只需在 Podfile 中添加以下行:
pod "GSLanguagePickerController"
在 UIKit.framework
中的传统本地化包名有多种类型。
[English Name].lproj
示例:English.lproj
、French.lproj
、German.lproj
、Spanish.lproj
[Language Id]_[Region Id].lproj
示例:zh_CN.lproj
、zh_HK.lproj
、zh_TW.lproj
、en_GB.lproj
[Language Id]-[Script Id].lproj
示例:zh-Hans.lproj
、zh-Hant.lproj
、es-ES.lproj
目前,类型 2 支持不够完善,因此使用 UIKit
包资源的 UIBarButtonSystemItem
等组件可能受到影响,直到应用程序重新启动。
gaosen,[email protected]
GSLanguagePickerController 可在 MIT 许可证下使用。有关更多信息,请参阅 LICENSE 文件。