首页 > 其他分享 >[IOS]如何在app里面改变语言

[IOS]如何在app里面改变语言

时间:2022-10-10 21:40:38浏览次数:377  
标签:语言 currentLanguage language app getInstance IOS LanguageTool NSBundle NSString


参考:​​https://stackoverflow.com/questions/9416923/ios-how-to-change-app-language-programmatically-without-restarting-the-app​

核心是使用



NSString *path = [[NSBundle mainBundle]pathForResource:currentLanguage ofType:@"lproj"];

if (path) {
localeBundle = [NSBundle bundleWithPath:path];

}else{
localeBundle= [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj" ]];
}


 改变localeBundle的值

 

 

思路:

1.使用

 

NSLocalizedStringFromTableInBundle(@"TNC_title", nil, localeBundle] , @""),

 可以实时变换不同的国际化文件

 

*国际化文件一般在文件目录系统是放在lproj后缀的文件夹中的:形式如zh-Hant.lproj(繁体)zh-Hants.lproj(简体)en.lproj(英文)

因此在上文的pathForResource:currentLanguage中也需要对应相应的文件名。

 

2.再刷新一遍UI的text获取

 

基于项目的代码示例:

建一个工具类.h:

 

#import <Foundation/Foundation.h>

@interface LanguageTool : NSObject



+(instancetype)getInstance;

- (NSBundle *)getLocaleBundle;

-(NSString *)getTap;

-(NSString *)getCurrentLanguage;

-(void)changeLanguage:(NSString*)language;


@end


.m:

#import "LanguageTool.h"
#import "SessionManager.h"

#define CNS @"zh"
#define EN @"en"
#define tap @"change_language"

static NSBundle *localeBundle = nil;
static NSString *currentLanguage = nil;

@interface LanguageTool()


@end

@implementation LanguageTool

//单例
+(instancetype)getInstance{
static LanguageTool *manager = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
manager = [[LanguageTool alloc] init];
});
return manager;
}


-(void)changeLanguage:(NSString*)language{

currentLanguage = language;

NSString *path = [[NSBundle mainBundle]pathForResource:language ofType:@"lproj"];

if (path && ![@"en" isEqualToString:language]) {
localeBundle = [NSBundle bundleWithPath:path];
}else{
localeBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj" ]];
}
}

//这个方法的目的是,如果什么都没有选择,就使用系统默认语言,否则使用用户选择的语言,并且不会因为关闭app而改变。
-(void)judgeLanguage{

//Get last change language
NSString *lastChangeLanguage = nil;
//使用一个持久化,保持上次的语言选择
lastChangeLanguage = [SessionManager getSession:[SessionManager getLastLanguageTap]];
NSLog(@"last chage language: %@",lastChangeLanguage);

//语言优先级:currentLanguage > lastChangeLanguage > system default language
//user 没有设定语言时:获取系统默认语言
if (!lastChangeLanguage) {
if (!currentLanguage) {
//获取系统默认语言:
//截取:zh-Hant-HK 去掉区域保留:zh-Hant
NSLog(@"-------system language:%@",[NSLocale preferredLanguages][0]);
currentLanguage = [[NSLocale preferredLanguages][0] substringToIndex:2];
if ([currentLanguage containsString:@"zh"]) {

currentLanguage = [NSString stringWithFormat:@"%@%@",currentLanguage,@"-Hant"];
}
}
}else if(!currentLanguage){
//当前没有切换语言,app内有设定语言,优先app内语言
currentLanguage = lastChangeLanguage;
}

}

- (NSBundle *)getLocaleBundle{

[self judgeLanguage];

NSLog(@"------current language :%@",currentLanguage);
NSLog(@"-------system language:%@",[NSLocale preferredLanguages][0]);

NSString *path = [[NSBundle mainBundle]pathForResource:currentLanguage ofType:@"lproj"];

if (path) {
localeBundle = [NSBundle bundleWithPath:path];

}else{
localeBundle= [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj" ]];
}
return localeBundle;
}

//标记
-(NSString *)getTap{
return tap;
}

-(NSString *)getCurrentLanguage{
// if (!currentLanguage) {
// //截取:zh-Hant-HK 去掉区域保留:zh-Hant
// currentLanguage = [[NSLocale preferredLanguages][0] substringToIndex:2];
// }

[self judgeLanguage];

NSLog(@"current language:%@",currentLanguage);
return currentLanguage;
}

@end



 

 

使用在需要切换语言的地方点击后调用:

 



//如果当前是英语就切换成繁体
if ([@"en" isEqualToString:[[LanguageTool getInstance] getCurrentLanguage]]) {
[self changeLanguage:@"zh-Hant"];
} else {
[self changeLanguage:@"en"];
}
//通知其他页面也切换语言
[self callLanguageChangeNotificationReceiver];

-(void)changeLanguage:(NSString*)language{

[[LanguageTool getInstance] changeLanguage:language];

//刷新某些UI text
[self initTableResource];

[_tableView reloadData];


}



 //例如这样刷新:

 

-(void)initTableResource{

_dataArray = @[NSLocalizedStringFromTableInBundle(@"Home", nil, [[LanguageTool getInstance] getLocaleBundle] , @""),
NSLocalizedStringFromTableInBundle(@"customization", nil, [[LanguageTool getInstance] getLocaleBundle] , @"")
,
NSLocalizedStringFromTableInBundle(@"TNC_title", nil, [[LanguageTool getInstance] getLocaleBundle] , @""),
NSLocalizedStringFromTableInBundle(@"localizable", nil, [[LanguageTool getInstance] getLocaleBundle] , @"")];

NSString *app_version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
_app_version_string = [NSString stringWithFormat:@"%@ %@",NSLocalizedStringFromTableInBundle(@"slider_version_info", nil, [[LanguageTool getInstance] getLocaleBundle] , @""),app_version];
if (_version_label) {
_version_label.text = _app_version_string;
}


[self initContentVersionLabel];

}



 

//设置通知:

 

-(void)callLanguageChangeNotificationReceiver{

[SessionManager setSession:[SessionManager getLastLanguageTap]
value:[[LanguageTool getInstance] getCurrentLanguage]];

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

[center postNotificationName:[[LanguageTool getInstance] getTap] object:nil];

}



 

被通知的页面接收通知,并刷新一下UI,操作并不复杂:



-(void)initNotification{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTextView) name:[[LanguageTool getInstance]getTap] object:nil];
}

-(void)refreshTextView{
_tncTextView.text = NSLocalizedStringFromTableInBundle(@"TNC_text", nil, [[LanguageTool getInstance] getLocaleBundle] , @"");
_navItem.title = NSLocalizedStringFromTableInBundle(@"TNC_title", nil, [[LanguageTool getInstance] getLocaleBundle] , @"");
}


 

标签:语言,currentLanguage,language,app,getInstance,IOS,LanguageTool,NSBundle,NSString
From: https://blog.51cto.com/u_15740686/5745299

相关文章

  • [ios]多个storyboard跳转
    1、单个storyboard跳转UIStoryboard*board=self.storyboard;HomeController*homevc=[boardinstantiateViewControllerWithIdentifier:@"homevc"];......
  • [IOS]如何结合XCODE使用git以及异常处理
    1.控制台cd到项目目录下,输入命令:gitinit 2.在gitserver创建xxx/project_name.git,输入命令:git--bareinit 3.本地控制台:gitadd.gitcommit-m"firstCommit"git......
  • IOS Push notification 摘要
    2.​​registerForRemoteNotificationTypes: is not supported ​​​​in​​​ ​​iOS 8.0 and later.报错​​解决办法可参考:http://stackoverflow.com/questi......
  • 小C语言--词法分析程序
    小C语言文法 1.<程序>→<main关键字>(){<声明序列><语句序列>}2.<声明序列>→<声明序列><声明语句>|<声明语句>|<空>3.<声明语句>→<标识符表>;4.<标识符表>→<标识符>......
  • Linux磁盘相关工具 -- iostat
    iostat主要用于监控系统设备的IO负载情况,根据这个可以看出当前系统的写入量和读取量,CPU负载和磁盘负载。iostat主要用于输出磁盘IO和CPU统计信息。1. iostat用法:iostat......
  • C语言找画笔(全网最详)
    题目:豆豆对数字的执着,让他在理科领域游刃有余,但他近乎疯狂的投入也使父母有些担心,为了让孩子能够全面发展,决定拓宽他的学习领域。正好家旁边有个绘画培训中心,父母就给豆豆报......
  • 【Azure 应用服务】Python Function App重新部署后,出现 Azure Functions runtime is u
    问题描述PythonFunctionApp重新部署后,出现AzureFunctionsruntimeisunreachable错误 问题解答在FunctionApp的门户页面中,登录Kudu站点(https://<yourfunction......
  • Go语言的接口和Rust的Trait的对比
    go语言的接口是鸭子的方式,即struct本身拥有的方法如果包含某个接口里定义的所有方法声明,则认为这个struct实现了该接口,举例子:typeAstruct{Faceint}//A结构体......
  • axios完整配置请求数据
    <scripttype="module">importaxiosfrom'./lib/axios.min.js'//axios完整配置请求语法:axios(config)axios({url:'/admin/detail',//url会拼接在......
  • 海外apple教学
    最近很多朋友问美区苹果,所以整理了一期注册教程,用处我就不多介绍了,需要的人自然是知道的.接下来让我们一步一步进行,第一步:准备一个邮箱国内的126、qq、163等等都可......