要点:注意要在切换完语言之后重新刷新APP的界面,否则新切换的语言不会生效
#import <Foundation/Foundation.h>
#import "Singleton.h"
#define kMyLanguage @"myLanguage"
@interface OpenHABLocalizedManage : NSObject
singleton_interface(OpenHABLocalizedManage) //此处要用到一个单例宏
- (NSString *)userLanguage;//获取应用当前语言
- (void)setUserlanguage:(NSString *)language;//设置当前语言
@end
实现文件内容如下:
#import "OpenHABLocalizedManage.h"
#import "NSBundle+Language.h"
@interface OpenHABLocalizedManage()
// 存储国际化键值对关系的字典
@property (nonatomic, strong) NSDictionary *locDic;
@end
@implementation OpenHABLocalizedManage
singleton_implementation(OpenHABLocalizedManage)
- (NSString *)userLanguage
{
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"]
&& ![[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] isEqualToString:@""]) {
return [[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"];
}
else
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
return currentLanguage;
}
return nil;
}
//设置语言
- (void)setUserlanguage:(NSString *)language{
// 设置语言
[NSBundle setLanguage:language];
// 然后将设置好的语言存储好,下次进来直接加载
[[NSUserDefaults standardUserDefaults] setObject:language forKey:kMyLanguage];
[[NSUserDefaults standardUserDefaults] synchronize];
}