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

参考: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] , @"");
}

资料:

1.http://blog.csdn.net/feng2qing/article/details/60479620

猜你喜欢

转载自jameskaron.iteye.com/blog/2395579