使用 swift iOS 刷新故事板 viewcontroller

Refresh Storyboard viewcontroller using swift iOS

我在所有 viewcontroller 中都有更改语言的按钮

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

我在我所有的FirstViewCONtroller、SecondController中继承了LanguageViewController如下

class FirstViewController: LanguageViewController {

}
class SecondController: LanguageViewController {

}

如果我调用 self.viewDidLoad(),它无法从故事板中定义的视图更改语言。如何重新加载故事板,以便在单击任何 viewcontroller 中的任何按钮时更改所有 viewcontroller 中的语言?谢谢!

如果我错了请纠正我。但我认为您不需要重新加载所有视图控制器。你只需要在它们显示时更新它们,视图控制器在呈现的视图控制器后面对用户不可见。

为此,您可以这样做:

var currentLanguage = ""

override func viewDidLoad() {
    currentLanguage = currentAppleLanguage()
    loadContentForLanguage(currentLanguage)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // this will be executed every time this sceen gets display
    if currentLanguage != currentAppleLanguage() {
          currentLanguage = currentAppleLanguage()
          loadContentForLanguage(currentLanguage)
    }
}

func loadContentForLanguage(_ currentLanguage: String) {
     //here it goes whatever you currently have in viewDidLoad
}

如果不能编译,我深表歉意,我的 swift 真的生锈了。

您可以使用 NotificationCenter 重新加载视图控制器的内容,这也会重新加载不可见的视图控制器的内容。

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