iOS获取特定语言的字符串的本地化版本 [英] iOS Get localized version of a string for a specific language

查看:136
本文介绍了iOS获取特定语言的字符串的本地化版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为iOS构建一个以英语和法语提供的应用程序。我已经阅读了一些关于国际化的教程,我对它的工作原理以及我需要做的事情有所了解。

I'm building an application for iOS that will be available in both English and French languages. I've read some tutorials around internationalization and I have an understanding of how it works and what I need to do.

我遇到的问题是有一个特定的我希望为英语用户加载法语字符串的情况。

The problem I'm having is there is a specific case where I want to load French strings for an English user.

我知道可以设置整个应用程序的语言,但是它需要重新启动应用程序在它生效之前。我想避免这种情况,而是能够根据需要选择加载法语或英语字符串。

I understand it's possible to set the language for the entire application, but that it requires the application to be restarted before it will take affect. I'd like to avoid this, and instead be able to pick to load French or English strings on demand.

是否可以从.strings文件加载字符串一种特定的语言以编程方式?

Is it possible to load strings from a .strings file for a specific language programmatically?

推荐答案

是的,这是可能的,但实现起来并不容易。

Yes, it is possible, but it is not that easy to accomplished.

我就是这样,我应该为GAI(Google Analytics for iOS)的ViewController发送一个相同的名称(适用于所有语言)。

I just have the case, where I should send one and the same name(for all languages) of a ViewController for GAI (Google Analytics for iOS).

前提条件:

1)我从这里使用NSBundle扩展https://stackoverflow.com/a/20257557/3883492 - 也许最好先查看那里。 (说实话,这真是天才)

1) I use the NSBundle extension from here https://stackoverflow.com/a/20257557/3883492 - maybe it is a good idea to look up there first. (It is pretty genius to be honest)

2)我使用的是swift 2

2) I am using swift 2

这是一个漂亮的简单的代码示例来说明我的想法:

Here is a pretty simple code sample to illustrate my idea:

func getFrenchString(forKey key: String) -> String {
    if let currentLanguage = (NSUserDefaults.standardUserDefaults().arrayForKey(AppleLanguages)?.first as? String) {
        if currentLanguage == "fr" {
            return NSLocalizedString(key, comment: "")
        }
        else {
            //the application is not currently on `fr`
            //change application to `fr`
            NSBundle.setLanguage("fr")

            //get the localized string on `fr`
            let frString = NSLocalizedString(key, comment: "")

            //return the application to the old language
            NSBundle.setLanguage(currentLanguage)

            return frString
        }
    }

    return ""
}

此外,您的项目中应该有fr.lproj文件夹和本地化字符串。

Also you should have "fr.lproj" folder with localised string in your project.

这篇关于iOS获取特定语言的字符串的本地化版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆