且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ios swift中本地化。如何在运行时更改应用程序语言

更新时间:2023-10-21 09:31:52

而不是使用 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.