N
N
Nikita2019-07-14 14:27:03
iOS
Nikita, 2019-07-14 14:27:03

Is it possible to set the language of the ViewController shown regardless of the device language?

I want to set the language of the ViewController (i.e. so that all the lines in it are loaded with the language that I need (on the Storyboard)), while the language may differ from the one installed on the device. Can it be done?
Example:
Device language: Russian
ViewController language: English

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Vorobei, 2019-07-14
@snitron

The code:

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 ""
}

preferred language is stored in NSUserDefaults , to get the value by key for a specific locale, temporarily change the language to French (you can change it to any other), get the value, and return the original language.
I'm sure you can make the method generic : for example, to receive the locale identifier as a parameter in the method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question