我的应用程序中有几个控制器。当我的应用程序调用一个控制器中的一个函数时,我想更新其他控制器的 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() 中调用所有其他控制器的 updateUI()
请帮忙,谢谢!
让视图控制器直接通信通常是一种非常糟糕的做法。我会用一个NSNotification
在视图控制器之间进行通信。按照惯例,通知名称以大写字母开头,以“通知”一词结尾。
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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)