iOS学习微信小程序开发iOS接下来要研究的知识点

iOS多语言的实现

2018-10-13  本文已影响204人  cyh老崔

一、说明

多语言一般为了实现下面两个目标:

  1. App展示的语言为目标客户的第一语言,如繁体中文、英语
  2. 在其它国家,默认展示语言为特定语言,如:英语

二、实现步骤

注:此例实现的语言有:繁体中文、英语,当iPhone设置的语言为其它语言时,默认展示英语

  1. Xcode 添加相应语言

    Xcode设置
  2. 选择目标语言后,弹框选择finish,最终如下:

    语言选择结果
  1. 设置不同语言下的应用名称
    3.1) 新建用来展示应用名称的多语言文件Strings File
    string 文件

3.2) 选择繁体中文,点击Localize

繁体中文

这时候,InfoPlist.strings文件就多了下拉箭头,打开后发现有多个文件,如上图

CFBundleDisplayName = "Space App";
CFBundleDisplayName = "国际化应用";
  1. 设置不同语言下,NSString的取值

Localizable.strings(English)

"facebook_login" = "Facebook Login";

Localizable.strings(Chinese(Traditional)):

"facebook_login" = "Facebook登錄";

由上我们可以看到命名规则:

4.2) 调用方法:

NSLocalizedString(@"facebook_login", nil)

第二个值comment一般传nil即可。此官方宏很简单,看官方解释即会使用

NSLocalizedStringFromTable(key, tbl, comment)

如果是在framework中,实现的多语言。需要将.string 文件打包在bundle中,用官方宏NSLocalizedStringFromTableInBundle来获取,假设此bundle名称为YHSDK.bundle

    NSString *mainBundlePath = [[NSBundle mainBundle] resourcePath];
    NSString *languageBundlePath = [mainBundlePath stringByAppendingPathComponent:@"YHSDK.bundle"];
    NSBundle *targetBundlePath = nil;
    targetBundlePath = [NSBundle bundleWithPath:languageBundlePath];
//    if ([[NSFileManager defaultManager] fileExistsAtPath:languageBundlePath]) {
//          NSLog(@"targetBundlePath:%@ 地址不存在", targetBundlePath);
//    }

    NSString *string = NSLocalizedStringFromTableInBundle(key, nil, targetBundlePath, nil);

三、其它注意事项

有时候iPhone设置成其它语言时,如法语,App展示的语言不是英语,而是繁体中文,是因为iPhone的设置导致的,将偏好的语言顺序中将繁体中文删除或调整到英文之后即可:

偏好的语言顺序
上一篇 下一篇

猜你喜欢

热点阅读