#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface InternationalControl : NSObject
+(NSBundle *)bundle;//获取当前资源文件
+(void)initUserLanguage;//初始化语言文件
+(NSString *)userLanguage;//获取应用当前语言
+(void)setUserlanguage:(NSString *)language;//设置当前语言
@end
static NSBundle *bundle = nil;
+ ( NSBundle * )bundle{
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"];
<pre class="cpp" name="code"> 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];//生成bundle
}
</pre>
+(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];
}
#import <UIKit/UIKit.h>
@interface YGViewController : UIViewController
@property (retain, nonatomic) IBOutlet UILabel *inviteLabel;//label
- (IBAction)changeLanguage:(id)sender;//点击事件
@property (retain, nonatomic) IBOutlet UIButton *btChange;//button
@end
- (void)viewDidLoad
{
//注册通知,用于接收改变语言的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLanguage) name:@"changeLanguage" object:nil];
[InternationalControl initUserLanguage];//初始化应用语言
NSBundle *bundle = [InternationalControl bundle];
NSString *inviteMsg = [bundle localizedStringForKey:@"invite" value:nil table:@"hello"];
NSString *buttonInfo = [bundle localizedStringForKey:@"buttonInfo" value:nil table:@"hello"];//table为hello.string的文件名
[_btChange setTitle:buttonInfo forState:UIControlStateNormal];
_inviteLabel.text = inviteMsg;
[super viewDidLoad];
}
- (IBAction)changeLanguage:(id)sender {
NSString *lan = [InternationalControl userLanguage];
if([lan isEqualToString:@"en"]){//判断当前的语言,进行改变
[InternationalControl setUserlanguage:@"zh-Hans"];
}else{
[InternationalControl setUserlanguage:@"en"];
}
//改变完成之后发送通知,告诉其他页面修改完成,提示刷新界面
[[NSNotificationCenter defaultCenter] postNotificationName:@"changeLanguage" object:nil];
}
-(void)changeLanguage{
[_btChange setTitle:[[InternationalControl bundle] localizedStringForKey:@"buttonInfo" value:nil table:@"hello"] forState:UIControlStateNormal];
_inviteLabel.text =[[InternationalControl bundle] localizedStringForKey:@"invite" value:nil table:@"hello"];
}