localization in ios swift. how can i change application language at run time

微笑、不失礼 提交于 2019-12-05 05:51:27

问题


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.

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?


回答1:


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

Loading the data from the bundle :

// 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)
    }
}

Replacing 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)
    }
}

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.




回答2:


Please don't do this. This leads to a very confusing user experience; people expect their apps to run in the system language they choose.

You'll also run into problems when it comes to UI and strings that you do not control, like system view controllers (e.g. sharing files) and formatters for dates, numbers, quantities, etc.

If every application had a language switcher by default, it would be a very cumbersome experience to go and select it for every app. This is why the localisation API is structured the way it is; if you use the system language fallback, then everything will work the way it should.



来源:https://stackoverflow.com/questions/35425788/localization-in-ios-swift-how-can-i-change-application-language-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!