1.首先添加需要支持的语言,默认支持英文,再添加中文即可
2.创建文件
如果只需要跟随系统语言切换,名字为Localizable,如果需要系统内切换,建议更改前其他名字.我刚开始使用Localizable,有问题.更换后暂时未发现问题.这里命名为Language.string
创建完成后,再勾选另外的语言,base暂时没发现有什么用
3,使用 我是使用单例管理语言 创建一个复制一下即可
// FKChangeLanguageTool.h
// unitTest
//
// Created by 高飞林 on 2018/7/5.
// Copyright © 2018年 高飞林. All rights reserved.
//
#import <Foundation/Foundation.h>
#define kChinese @"zh-Hans"
#define kEnglish @"en"
@interface FKChangeLanguageTool : NSObject
@property (nonatomic, strong) NSBundle *languageBundle;
+ (instancetype)shareTool;
- (void)changeLangueWithKey:(NSString *)key;
@end
#import "FKChangeLanguageTool.h"
#import "AppDelegate.h"
@implementation FKChangeLanguageTool
+ (instancetype)shareTool {
static FKChangeLanguageTool *tool = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
tool = [[FKChangeLanguageTool alloc] init];
[tool resetBundleNeedReload:NO];
});
return tool;
}
- (void)changeLangueWithKey:(NSString *)key {
[[NSUserDefaults standardUserDefaults] setObject:key forKey:@"appLanguage"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self resetBundleNeedReload:YES];
}
- (void)resetBundleNeedReload:(BOOL)reload {
[NSThread sleepForTimeInterval:0.1];
NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"appLanguage"];
if (!language) {
NSArray *languages = [NSLocale preferredLanguages];
language = [languages objectAtIndex:0];
if ([language hasPrefix:kChinese]) {
//开头匹配
[[NSUserDefaults standardUserDefaults] setObject:kChinese forKey:@"appLanguage"];
language = kChinese;
}else{
[[NSUserDefaults standardUserDefaults] setObject:kEnglish forKey:@"appLanguage"];
language = kEnglish;
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
self.languageBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]];
if (reload) {
//这是就是给window重新创建rootViewController,需要你们定义自己的方法
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[delegate setRoot];
}
}
@end
具体使用
//创建宏
#define Localized(key) NSLocalizedStringFromTableInBundle(key, @"Language", [FKChangeLanguageTool shareTool].languageBundle, nil)
//使用
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
label.text = Localized(@"关注");
[self.view addSubview:label];
//切换中文
[[FKChangeLanguageTool shareTool] changeLangueWithKey:kChinese];
//切换英文
[[FKChangeLanguageTool shareTool] changeLangueWithKey:kEnglish];
这样就可以实现app内切换语言了,踩过了不少坑.