Search code examples
iosswiftuiviewcontrollerlocalizationviewcontroller

Refresh Storyboard viewcontroller using swift iOS


Im having button in all viewcontrollers to change language

LanguageViewController.swift

class LanguageViewController: UIViewController {
     @IBAction func actionChange(_ sender: Any) {
          L102Language.currentAppleLanguage()
          L102Language.setAppleLAnguageTo(lang: "en")
          // below code to refresh storyboard
          self.viewDidLoad()
     }
}

L102Language.swift

class func currentAppleLanguage() -> String{
        let userdef = UserDefaults.standard
        let langArray = userdef.object(forKey: APPLE_LANGUAGE_KEY) as! NSArray
        let current = langArray.firstObject as! String
        let endIndex = current.startIndex
        let currentWithoutLocale = current.substring(to: current.index(endIndex, offsetBy: 2))
        return currentWithoutLocale
    }

    /// set @lang to be the first in Applelanguages list
    class func setAppleLAnguageTo(lang: String) {
        let userdef = UserDefaults.standard
        userdef.set([lang,currentAppleLanguage()], forKey: APPLE_LANGUAGE_KEY)
        userdef.synchronize()
    } 

I inherited LanguageViewController in all my FirstViewCOntroller, SecondController as below

class FirstViewController: LanguageViewController {

}
class SecondController: LanguageViewController {

}

If I call self.viewDidLoad() it fails to change language from view defined in storyboard. How to reload storyboard, so that the language should change in all viewcontroller,if any button from any viewcontroller is clicked? Thanks!


Solution

  • You can use NotificationCenter for reloading the view controllers content, this will also reload the content of view controllers that are not visible.

    extension Notification.Name {
        static let didChangeLanguage = Notification.Name("didChangeLanguage")
    }
    
    override func viewDidLoad() {
        //Add a listener
        NotificationCenter.default.addObserver(self, selector: #selector(onDidChangeLanguage(_:)), name: .didChangeLanguage, object: nil)
    
    }
    
    @IBAction func actionChange(_ sender: Any) {
        L102Language.currentAppleLanguage()
        L102Language.setAppleLAnguageTo(lang: "en")
        // Notify about the change.
        NotificationCenter.default.post(name: .didChangeLanguage, object: self, userInfo: nil)
    }
    
    @objc func onDidChangeLanguage(_ notification:Notification) {
        // reload content using selected language.
    }