你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> [iOS]如何在iOS開發中切換顯示語言實現國際化

[iOS]如何在iOS開發中切換顯示語言實現國際化

編輯:IOS開發綜合

1.在Project設置,添加中英兩種語言:

/

 

 

2.新建Localizable.strings文件,作為多語言對應的詞典,存儲多種語言,點擊右側Localization,勾選中英:

/

 

3.添加一個字段,

 

在English中,添加:SUBMIT_BTN_TITLE = Go;

在Chinese中,添加:SUBMIT_BTN_TITLE = 開始;
 

4.一個工具類GDLocalizableController,用來切換本地語言:
//
//  GDLocalizableController.h
//  guide-book
//
//  Created by why on 7/16/14.
//  Copyright (c) 2014 why. All rights reserved.
//

#import 

@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));


 

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved