在ios swift中本地化。如何在运行时更改应用程序语言 [英] localization in ios swift. how can i change application language at run time

查看:209
本文介绍了在ios swift中本地化。如何在运行时更改应用程序语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ios swift中创建应用程序。现在我想用双语制作应用程序,所以从编辑菜单我只是导出和导入本地化。它为我创建了两个文件。

i am creating app in ios swift. now i want to make app in dual language so from editor menu i just export and import for localization. its create two file for me.

现在我想在我的应用的第一页上放两个按钮。当用户按下按钮1我想加载英语。如果用户按下按钮2我想加载土耳其语。那我怎么能在swift中做到这一点?

now i want to put two button on first page of my app. and when user press button 1 i want to load english language. and if user press button 2 i want to load turkish language. so how can i do this in swift?

推荐答案

而不是使用 NSLocalizedString 本地化您的应用程序的方法,根据所选语言加载可本地化的字符串,并从您的代码中使用它。

Instead of using NSLocalizedString method to localize your App, load the localizable strings according to the language selected and use it from your code.

从数据包加载数据:

// Exemple with english language
if let path = NSBundle(forClass:object_getClass(self)).URLForResource("Localizable", withExtension: "strings", subdirectory: nil, localization: "en")?.path {
    if NSFileManager.defaultManager().fileExistsAtPath(path)     {
        // Keep a reference to this dictionary
        dicoLocalisation = NSDictionary(contentsOfFile: path)
    }
}

替换NSLocalizedString:

func localizedStringForKey(key:String) -> String { 
    // First we check if the dictionary exists       
    if let dico = dicoLocalisation {

        if let localizedString = dico[key] as? String {
            // If the localization exists, return it
            return localizedString
        }  else {
            // Returns the key if no String was found
            return key
        }
    } else {
        // If not, we can use the NSLocalizedString function
        return NSLocalizedString(key, comment: key)
    }
}

如果你想快速处理这个问题,我已经在 Github ,它允许您从应用程序的任何位置切换语言,甚至可以保存,以便进一步启动应用程序。实现与我解释的几乎相同。

If you want to handle this quickly, I've made a custom localisator class available on Github, which allow you to switch language from anywhere in the app and even save if for further launches of the app. The implementation is pretty much the same as what I've explained.

这篇关于在ios swift中本地化。如何在运行时更改应用程序语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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