简体   繁体   中英

Localize storyboard programatically on the fly

My app allows user to change country, so if they change to Thailand, I am supposed to update my storyboard etc's language. P/S: I've seen a lot of people say if you relaunch the app you'll be fine, but that's really a user experience issue I wanted to prevent. The following is my current attempt, it works fine for programatically created/modified/defined text but it doesn't update the text on my storyboard :(

import UIKit
class LocalizationHelper: NSObject {
    static var bundle: NSBundle?
    static let sharedInstance = LocalizationHelper()

    func localizedStringForKey(key: String, comment: String) -> String {
        return (LocalizationHelper.bundle?.localizedStringForKey(key, value: comment, table: nil))!
    }

    func setLanguage(language: String) {

        NSUserDefaults.standardUserDefaults().setObject(language, forKey: "LocalizedStringUserDefaultsKey")
        NSUserDefaults.standardUserDefaults().synchronize()


        if let path = NSBundle.mainBundle().pathForResource(language, ofType: "lproj") {

            print(language)
            print(language)

            LocalizationHelper.bundle = NSBundle(path: path)
            print(LocalizationHelper.bundle)
        } else {
            NSUserDefaults.standardUserDefaults().setObject("Base", forKey: "LocalizedStringUserDefaultsKey")
            NSUserDefaults.standardUserDefaults().synchronize()
            LocalizationHelper.bundle = NSBundle.mainBundle()
        }
    }

}

The print statement result is

Optional(NSBundle </var/mobile/Containers/Bundle/Application/91776A02-BADA-4EC9-A451-45A453B84C83/Appname.app/th.lproj> (not yet loaded))

Does this matter anything? For the record, I referenced this

https://github.com/jslim89/JSLocalizedString

P/S: I have also have my Main.string(Thai) in my Main.storyboard(Base) ready, just that they only update when I change System Language :(

I believe you have outlets defined for each UI component in storyboard. You can simply localize them by calling NSLocalizedString :

self.title = NSLocalizedString("MyTitle", nil);

The other option could be to have multiple storyboard one for each supported language. Once user change the country, based on the supported language pick the right storyboard. Something like this:

let storyboard = UIStoryboard(name: "MainStoryboard_English", bundle: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM