ios应用内切换设置语言,不跟系统变化


http://blog.csdn.net/yang8456211/article/details/12031667

//
//  LanInternational.h
//  MyLaenLanguageSet
//
//  Created by laizhenjie on 8/21/14.
//  Copyright (c) 2014 Laencho. All rights reserved.
//  语言设置文件;

#import 

@interface LanInternational : NSObject


+(NSBundle *)localBundle;//获取当前资源文件

+(void)initUserLanguage;//初始化语言文件

+(NSString *)userLanguage;//获取应用当前语言

+(void)setUserlanguage:(NSString *)language;//设置当前语言

+(NSString *)appleLanguage; //系统默认语言;

@end


//
//  LanInternational.m
//  MyLaenLanguageSet
//
//  Created by laizhenjie on 8/21/14.
//  Copyright (c) 2014 Laencho. All rights reserved.
//

#import "LanInternational.h"
#define USER_SETTED_LANGUAGE @"userSettedLanguage"  //用户设置语言标识;

@implementation LanInternational

static NSBundle *bundle = nil;

+ ( NSBundle * )localBundle{
    [LanInternational initUserLanguage];
    return bundle;
    
}



+(void)initUserLanguage{
   
    //先从用户设置的语言里读取语言设置;
    //如果用户没有设置语言,就从系统读取语言设置;
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *string = [def valueForKey:@"userLanguage"];
    
    if(string.length == 0){
        
        //获取系统当前语言版本(中文zh-Hans,英文en)
        NSArray* languages = [def objectForKey:@"AppleLanguages"];
        NSString *current = [languages objectAtIndex:0];
        string = current;
        [def setValue:current forKey:@"userLanguage"];
        
        [def synchronize];
    }
    
    //获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:string ofType:@"lproj"];
    bundle = [NSBundle bundleWithPath:path];
}

//获取当前语言标识;
+(NSString *)userLanguage{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *language = [def valueForKey:@"userLanguage"];
    return language;
}

//语言设置;
+(void)setUserlanguage:(NSString *)language{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    //1.第一步改变bundle的值
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj" ];
    bundle = [NSBundle bundleWithPath:path];
    
    //2.持久化
    [def setValue:language forKey:@"userLanguage"];
    [def synchronize];
}

//系统默认的语言;
+ (NSString *)appleLanguage{

    //获取系统当前语言版本(中文zh-Hans,英文en)
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [def objectForKey:@"AppleLanguages"];
    NSString *appLan = [languages objectAtIndex:0];
    return appLan;
}

@end


封装成宏来使用:

//语言设置相关;
#define LocalString(key) \
        [[LanInternational localBundle] localizedStringForKey:(key) value:@"" table:nil] //对key进行语言读取
#define LocalLanSet(lan) \
        [LanInternational setUserlanguage:(lan)] //设置语言;
#define LocalCurrLan \
        [LanInternational userLanguage] //读取应用当前的语言;
#define LocalAppleLan \
        [LanInternational appleLanguage]  //系统默认设置语言;

#define APPLE_LAGUAGES @"AppleLanguages" //系统语言的key
#define USER_LANGUAGE @"userLanguage"  //用户设置的语言key;与LanInternational里的字符一定要一样;

nsbundle



你可能感兴趣的:(ios应用内切换设置语言,不跟系统变化)