iOS (2018最新) 实现多语言开发(二),手动切换本地语言

上一篇文章了谈到了如何根据本地语言环境显示不同的语言.这一小节着重讲解如何在手动本地切换语言.效果如下:


93YNP.gif

要设置语言,原理比较简单.
切换语言实际上就是去获取每种语言所对应的后缀是.lproj的文件夹.APP切换语言的时候实际上就是去获取这些文件夹下面的STLocalizable.strings文件.想要获取文件key对应的value的时候只需要改变pathForResource后面的名称即可

NSString *path = [[NSBundle mainBundle] pathForResource:@"zh-Hans" ofType:@"lproj"];
NSString *labelString = [[NSBundle bundleWithPath:path] localizedStringForKey:@"label" value:nil table:@"STLocalizable"];
NSLog(@"result: %@", labelString);
//输出:MultiLanguage[1887:72599] result: 标签

在这里贴出两个核心类(亲测可用)

#import 

@interface NSBundle (Language)

+ (void)setLanguage:(NSString *)language;

@end


#import "NSBundle+Language.h"
#import 

static const char _bundle = 0;

@interface BundleEx : NSBundle

@end

@implementation BundleEx

- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName {
    NSBundle *bundle = objc_getAssociatedObject(self, &_bundle);
    return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [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]);
    });
    
    objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
#import 

@interface ChangeLanguage : NSObject
+(NSBundle *)bundle;//获取当前资源文件
+(void)initUserLanguage;//初始化语言文件
+(NSString *)userLanguage;//获取应用当前语言
+(void)setUserlanguage:(NSString *)language;//设置当前语言
@end

#import "ChangeLanguage.h"

@implementation ChangeLanguage
static NSBundle *bundle = nil;
+ ( NSBundle * )bundle{
    
    return bundle;
}

//首次加载的时候先检测语言是否存在
+(void)initUserLanguage{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    NSString *currLanguage = [def valueForKey:LocalLanguageKey];
    
    if(!currLanguage){
        NSArray *preferredLanguages = [NSLocale preferredLanguages];
        currLanguage = preferredLanguages[0];
        if ([currLanguage hasPrefix:@"en"]) {
            currLanguage = @"en";
        }else if ([currLanguage hasPrefix:@"zh"]) {
            currLanguage = @"zh-Hans";
        }else currLanguage = @"en";
        [def setValue:currLanguage forKey:LocalLanguageKey];
        [def synchronize];
    }
    
    //获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:currLanguage ofType:@"lproj"];
    bundle = [NSBundle bundleWithPath:path];//生成bundle
}

//获取当前语言
+(NSString *)userLanguage{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    NSString *language = [def valueForKey:LocalLanguageKey];
    
    return language;
}
//设置语言
+(void)setUserlanguage:(NSString *)language{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *currLanguage = [userDefaults valueForKey:LocalLanguageKey];
    if ([currLanguage isEqualToString:language]) {
        return;
    }
    [userDefaults setValue:language forKey:LocalLanguageKey];
    [userDefaults synchronize];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj" ];
    bundle = [NSBundle bundleWithPath:path];
}
@end

使用的时候很方便,直接创建上面两个类.拖入你的工程项目中
点击切换的时候,注意下面的额language这个参数就是设置的语言.设置之后需要重新刷新界面.我们只需要给当前的keyWindow.rootViewController重新赋值即可.代码如下的.例如

if ([self.chooseLangTextFiled.text isEqualToString:@"简体中文/chinese"]) {
        [self changeLanguageTo:@"zh-Hans"];
    }
    if ([self.chooseLangTextFiled.text isEqualToString:@"英文/english"]) {
        [self changeLanguageTo:@"en"];
    }
    if ([self.chooseLangTextFiled.text isEqualToString:@"缅甸/Burma"]) {
        [self changeLanguageTo:@"en"];
    }
//更换
- (void)changeLanguageTo:(NSString *)language {
    // 设置语言
    [NSBundle setLanguage:language];
    
    // 然后将设置好的语言存储好,下次进来直接加载
    [[NSUserDefaults standardUserDefaults] setObject:language forKey:@"myLanguage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.loginType.length!=0) {
        SJLoginViewController *loginVC=[[SJLoginViewController alloc] init];
        YGKNavigationVC *navc=[[YGKNavigationVC alloc] initWithRootViewController:loginVC];

        [UIApplication sharedApplication].keyWindow.rootViewController = navc;

    }else
    {
        // 我们要把系统window的rootViewController替换掉
        YGKJTabbarVC *tab = [[YGKJTabbarVC alloc] init];
        [UIApplication sharedApplication].keyWindow.rootViewController = tab;
        // 跳转到设置页
        tab.selectedIndex = 2;
    }
    
   
    
    
}

下面是一些常用的方法.一并分享给大家

#define LanguageKey @"appLanguage"
//获取当前语言
[[NSUserDefaults standardUserDefaults] objectForKey:LanguageKey];
//获取首选语言顺序
[NSLocale preferredLanguages];
//获取首选语言第一语言
[[NSLocale preferredLanguages] objectAtIndex:0];
//获取系统所有语言
[NSLocale availableLocaleIdentifiers];
//获取当前语言文件路径
NSString *currentLanguage = [[NSUserDefaults standardUserDefaults] ;objectForKey:LanguageKey];
NSString *path = [[NSBundle mainBundle] pathForResource:currentLanguage ofType:@"lproj"];
//根据key获取当前语言对应的本地字符串(参数value:如果key是nil或key在表中找不到本地化字符串,则返回的值。)
NSString *value = [[NSBundle bundleWithPath:path] localizedStringForKey:@"label" value:nil table:@"TiLocalizable"];

有问题可直接咨询我,欢迎在评论区指出不足,或者优化建议
承接APP,小程序,公众号开发. 性价比高.+V信:17723566468 有单子也可找我一起做哦

你可能感兴趣的:(iOS (2018最新) 实现多语言开发(二),手动切换本地语言)