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

国际化默认 语言设置成英语 完美解决_第1张图片//

//  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

你可能感兴趣的:(ios开发技术分享,iOS,开发技术分享)