码迷,mamicode.com
首页 > 移动开发 > 详细

[iOS]怎样在iOS开发中切换显示语言实现国际化

时间:2017-05-28 10:50:42      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:define   nsobject   ==   south   href   article   pop   objc   gravity   

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 <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开发中切换显示语言实现国际化

标签:define   nsobject   ==   south   href   article   pop   objc   gravity   

原文地址:http://www.cnblogs.com/cxchanpin/p/6915143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!