我的应用程序中有多个 Controller 。当我的应用程序调用一个 Controller 中的一个函数时,我想更新其他 Controller 的 UI。我怎样才能做到这一点?
class FirstViewController: UIViewController {
func updateUI {...}
}
class SecondViewController: UIViewController {
func updateUI {...}
}
class ThirdViewController: UIViewController{
func updateAllUI {...} # I want call FirstViewController().updateUI() and SecondViewController().updateUI() here
}
但 FirstViewController() 意味着我创建了一个我不想要的新 FirstViewController,并且 FirstViewController 已经创建。那么我如何在 updateAllUI() 中调用所有其他 Controller 的 updateUI()
请帮忙,谢谢!
最佳答案
让 View Controller 直接通信通常是一种非常糟糕的做法。我会使用 NSNotification
在 View Controller 之间进行通信。通知名称以大写字母开头并以“通知”一词结尾是惯例。
class FirstViewController: UIViewController {
func updateUI {...}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", name:"TimeToUpdateTheUINotificaiton", object: nil)
}
override deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
class SecondViewController: UIViewController {
func updateUI {...}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", name:"TimeToUpdateTheUINotificaiton", object: nil)
}
override deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
class ThirdViewController: UIViewController{
func updateAllUI {
NSNotificationCenter.defaultCenter().postNotificationName("TimeToUpdateTheUINotificaiton", object: nil)
}
}
关于ios - 我如何快速更新其他 Controller 的用户界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31259028/