gkl*_*lka 7 localization ios uistoryboard
我正在为我的应用程序使用单个本地化的Storyboard.该应用程序必须有一个选项来动态更改语言.到目前为止,我想出了如何更改应用程序启动期间使用的语言:
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", @"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate
Run Code Online (Sandbox Code Playgroud)
并设法通过删除关键窗口的所有子视图重新加载我的整个应用程序,从故事板重新加载初始视图控制器并使其成为新的根视图控制器.(它有一些问题,比如管理开放资源,但可以做到.)
我唯一想知道的是如何强制iOS以新语言重新加载故事板?似乎故事板以某种方式缓存,并且-UIStoryboad:stroyboardWithName:fromNib不会完全重新加载它,所以它出现在最后一种语言中.
我已经考虑了其他两个选择:
每种语言都有不同的故事板文件(这是无法管理的,我不想这样做)
在我的所有视图控制器中使用事件侦听器,它们响应语言更改并在UI上设置新字符串(每次从故事板中实例化任何接口元素时也必须调用它).这个解决方案需要更多的时间,而不是我们想要花费的时间,并且还大大增加了错误的可能性.
还有一些更聪明的方法吗?我不想保持我的应用程序的当前状态,所以重新启动它就像它被杀死和实现似乎是一个合理的解决方案.
gkl*_*lka 13
所以我发现问题在于我的故事板的基本翻译,这意味着我只有一个Storyboard文件和一个.strings文件.使用Base翻译无法完成,Apple不支持.
所以我的解决方法如下:
将基本翻译转换为每种语言的一个Storyboard(当您单击Storyboard并将类型设置为Strings中的Storyboard时,您可以在Xcode中执行此操作).您可以在最后删除Base.
翻译故事板中的字符串
在语言更改按钮的按钮处理程序中,执行以下操作:
(我使用tab控制器作为根控制器,您应该将其更改为根控制器类型.)
[[NSDefaults standardDefaults] setObject:[NSArray arrayWithObject:@"hu"] forKey:@"AppleLanguages"];
[[NSDefaults standardDefaults] synchronize];
GKAppDelegate *appDelegate = (GKAppDelegate *)[[UIApplication sharedApplication] delegate];
UITabBarController* tabBar = (UITabBarController *)appDelegate.window.rootViewController;
// reload the storyboard in the selected language
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:appDelegate.lang ofType:@"lproj"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:bundle];
// reload the view controllers
UINavigationController *placesTab = (UINavigationController *)[storyBoard instantiateViewControllerWithIdentifier:@"placesTab"];
UINavigationController *informationTab = (UINavigationController *)[storyBoard instantiateViewControllerWithIdentifier:@"informationTab"];
// set them
NSArray *newViewControllers = @[placesTab, informationTab];
tabBar.viewControllers = newViewControllers;
Run Code Online (Sandbox Code Playgroud)
在您的appname.pch文件中:
#define currentLanguageBundle [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"]]
Run Code Online (Sandbox Code Playgroud)
你应该改变这一切:
NSLocalizedString(@"key", @"comment")
Run Code Online (Sandbox Code Playgroud)
对此:
NSLocalizedStringFromTableInBundle(@"key", nil, currentLanguageBundle, @"");
Run Code Online (Sandbox Code Playgroud)
请注意,我删除了第二个参数,评论.看起来非ASCII字母的注释可能会带来麻烦,所以最好在这一点上避免使用它们.
这种方法的冒险:
您可以使用系统工具将字符串收集到.strings文件
更改语言时,UI不会闪烁
你不必写很多代码或使用很多网点
当用户按下按钮时,语言changig代码只需运行一次
我希望这有帮助,也许你可以改进我的解决方案.
| 归档时间: |
|
| 查看次数: |
10979 次 |
| 最近记录: |