其他分享
首页 > 其他分享> > 国际化默认 语言设置成英语 完美解决

国际化默认 语言设置成英语 完美解决

作者:互联网

//

//  HLLanguageUtil.m

//  eCarry

//

//  Created by whde on 19/7/9.

//  Copyright © 2019年 sxw. All rights reserved.

//

 

#import "HLLanguageUtil.h"

static NSBundle *bundle = nil;

@implementation HLLanguageUtil

 

// 获取Bundle

+(NSBundle *)bundle{

    if (bundle == nil) {

        NSString *userLanguage = [[NSUserDefaults standardUserDefaults] valueForKey:@"userLanguage"];

        if (userLanguage) {

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

            bundle = [NSBundle bundleWithPath:path];

            return bundle;

        } else {

            bundle = [NSBundle mainBundle];

        }

    }

    return bundle;

}

 

// 设置Bundle

+ (void)setBundle:(nullable NSString *)userLanguage{

    if (userLanguage) {

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

        bundle = [NSBundle bundleWithPath:path];

    } else {

        bundle = [NSBundle mainBundle];

    }

}

 

// 获取当前语言

+ (Language)getCurrentLanguage {

    

    NSArray *langArray = [[NSUserDefaults standardUserDefaults] arrayForKey:@"AppleLanguages"];

    NSString *language = langArray[0];

    if (language) {

#if DEBUG

        NSLog( @"%@" , language);

#endif

    } else{

        return Language_Default;

    }

    if ([language rangeOfString:@"en"].location != NSNotFound) {

        return Language_EN;

    } else if ([language rangeOfString:@"Hans"].location != NSNotFound) {

        return Language_Hans;

    } else if ([language rangeOfString:@"Hant"].location != NSNotFound) {

        return Language_Hant;

    } else {

        return Language_Default;

    }

}

 

// 设置语言

+ (void)setCurrentLanguage:(Language)language{

    switch (language) {

        case Language_Default:

            [[NSUserDefaults standardUserDefaults] setValue:@"en" forKey:@"userLanguage"];

            [self setBundle:@"en"];

            break;

        case Language_EN:

            [[NSUserDefaults standardUserDefaults] setValue:@"en" forKey:@"userLanguage"];

            [self setBundle:@"en"];

            break;

        case Language_Hans:

            [[NSUserDefaults standardUserDefaults] setValue:@"zh-Hans" forKey:@"userLanguage"];

            [self setBundle:@"zh-Hans"];

            break;

        case Language_Hant:

            [[NSUserDefaults standardUserDefaults] setValue:@"zh-Hant" forKey:@"userLanguage"];

            [self setBundle:@"zh-Hant"];

            break;

        default:

            break;

    }

    [[NSUserDefaults standardUserDefaults] synchronize];

    [[NSNotificationCenter defaultCenter] postNotificationName:LANGUAGE_CHANGE_NOTIFICATION object:nil];

}

@end

标签:国际化,language,Language,完美,bundle,NSBundle,默认,NSUserDefaults,userLanguage
来源: https://blog.csdn.net/sxwlyp924app/article/details/95209464