[iOS]怎樣在iOS開發中切換顯示語言實現國際化
阿新 • • 發佈:2017-05-28
art out title oca standard 文件 creat mit 工具類
6.使用:
1.在Project設置,加入中英兩種語言:
2.新建Localizable.strings文件,作為多語言相應的詞典,存儲多種語言,點擊右側Localization,勾選中英:
3.加入一個字段,
在English中,加入:"SUBMIT_BTN_TITLE" = "Go";
在Chinese中,加入:"SUBMIT_BTN_TITLE" = "開始";
// // GDLocalizableController.h // guide-book // // Created by why on 7/16/14. // Copyright (c) 2014 why. All rights reserved. // #import <Foundation/Foundation.h> @interface GDLocalizableController : NSObject +(NSBundle *)bundle;//獲取當前資源文件 +(void)initUserLanguage;//初始化語言文件 +(NSString *)userLanguage;//獲取應用當前語言 +(void)setUserlanguage:(NSString *)language;//設置當前語言 @end // // GDLocalizableController.m // guide-book // // Created by why on 7/16/14. // Copyright (c) 2014 why. All rights reserved. // #import "GDLocalizableController.h" @implementation GDLocalizableController static NSBundle *bundle = nil; + ( NSBundle * )bundle{ return bundle; } +(void)initUserLanguage{ NSUserDefaults *def = [NSUserDefaults standardUserDefaults]; NSString *string = [def valueForKey:@"userLanguage"]; if(string.length == 0){ //獲取系統當前語言版本號 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];//生成bundle } +(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]; } @end
5. 自己定義一個宏方便處理:
// ----- 多語言設置 #define CHINESE @"zh-Hans" #define ENGLISH @"en" #define GDLocalizedString(key) [[GDLocalizableController bundle] localizedStringForKey:(key) value:@"" table:nil]
6.使用:
[GDLocalizableController setUserlanguage:CHINESE]; NSLog(GDLocalizedString(@"SUBMIT_BTN_TITLE")); [GDLocalizableController setUserlanguage:ENGLISH]; NSLog(GDLocalizedString(@"SUBMIT_BTN_TITLE"));
參考資料:iOS 應用程序內部國際化,不尾隨系統語言
[iOS]怎樣在iOS開發中切換顯示語言實現國際化