如果公司的iOS应用需要支持歪果仁,那么多语言是必不可少的,至少要支持一门英语吧,要不然还不如不做,关于iOS本地化网上也看了不少文章,总是感觉离工程实战少了点感觉,我们先简单看一下Demo效果:
App中多语言设置起始很简单,主要步骤如下:
1.项目设置需要支持的语言:
2.UIStoryBoard,xib及strings多语言设置:
UIStoryBoard多语言设置:
strings文件设置:
3.iOS本地化默认支持的是Localizable.strings文件:
self.localizedLabel.text=NSLocalizedString(@"Hello", nil);
当然我们也可以自定义一个FlyElephant.strings的文件:
self.localizedLabel.text=NSLocalizedStringFromTable(@"Hello", @"FlyElephant", nil);
4.语言切换:
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];
5.AppDelegate设置:
#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];
}
6.NSBundle扩展:
@interface NSBundle (Language)
+ (void)setLanguage:(NSString *)language;
@end
#import "NSBundle+Language.h"
#import <objc/runtime.h>
static const char kBundleKey = 0;
@interface BundleEx : NSBundle
@end
@implementation BundleEx
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
NSBundle *bundle = objc_getAssociatedObject(self, &kBundleKey);
if (bundle) {
return [bundle localizedStringForKey:key value:value table:tableName];
}
else {
return [super localizedStringForKey:key value:value table:tableName];
}
}
@end
@implementation NSBundle (Language)
+ (void)setLanguage:(NSString *)language
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
object_setClass([NSBundle mainBundle],[BundleEx class]);
});
id value = language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil;
objc_setAssociatedObject([NSBundle mainBundle], &kBundleKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
基本的应用内语言切换功能可以实现了,如果对于App多语言有什么问题,欢迎评论区共同探讨~