iOS猿媛圈专业知识分享(iOS)iOS技术专题

iOS本地化-语言切换

2016-06-01  本文已影响507人  FlyElephant

如果公司的iOS应用需要支持歪果仁,那么多语言是必不可少的,至少要支持一门英语吧,要不然还不如不做,关于iOS本地化网上也看了不少文章,总是感觉离工程实战少了点感觉,我们先简单看一下Demo效果:

Language.gif

App中多语言设置起始很简单,主要步骤如下:
1.项目设置需要支持的语言:


Snip20160601_1.png

2.UIStoryBoard,xib及strings多语言设置:
UIStoryBoard多语言设置:


Paste_Image.png

strings文件设置:


Snip20160601_5.png

3.iOS本地化默认支持的是Localizable.strings文件:
<pre><code>self.localizedLabel.text=NSLocalizedString(@"Hello", nil);</code></pre>
当然我们也可以自定义一个FlyElephant.strings的文件:
<pre><code>self.localizedLabel.text=NSLocalizedStringFromTable(@"Hello", @"FlyElephant", nil);</code></pre>

4.语言切换:

<pre><code>`
NSString *code;
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"AppleLanguages"][0] isEqual:@"en"]) {
code=@"zh-Hans";
}else{
code=@"en";
}
[[NSUserDefaults standardUserDefaults] setObject:@[code] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDelegate reloadRootContoller:code];`</code></pre>

5.AppDelegate设置:
<pre><code>`

pragma mark - RootViewController

-(void)loadRootViewController{
ViewController *rootController=[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewController"];
self.window.rootViewController=rootController;
}

pragma mark - Public

-(void)reloadRootContoller:(NSString *)code{
[NSBundle setLanguage:code];
[self loadRootViewController];
}`</code></pre>

6.NSBundle扩展:
<pre><code>`
@interface NSBundle (Language)

@end`</code></pre>

<pre><code>`

import "NSBundle+Language.h"

import <objc/runtime.h>

static const char kBundleKey = 0;

@interface BundleEx : NSBundle

@end

@implementation BundleEx

@end

@implementation NSBundle (Language)

@end`</code></pre>

基本的应用内语言切换功能可以实现了,如果对于App多语言有什么问题,欢迎评论区共同探讨~

上一篇 下一篇

猜你喜欢

热点阅读