我的应用程序中有几个控制器.当我的应用程序在一个控制器中调用一个函数时,我想更新其他控制器的UI.我怎样才能做到这一点? class FirstViewController: UIViewController { func updateUI {...} }cl
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) } }