如何在swift中更新其他控制器的UI?

我的应用程序中有几个控制器。 当我的应用程序在一个控制器中调用一个函数时,我想更新其他控制器的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) } } 

消除括号。 调用类函数时不要使用它们。

FirstViewController.updateUI()

那就是说…你要做的事情至少可以说很奇怪。 您不应该使用类函数来修改类实例的属性。 如果同时在屏幕上同时具有两个View控制器,则应该使用父控制器来命令它们在需要时更新其UI。

如果它们不是同时在屏幕上,您实际上不需要更新两个UI。

如果您希望所有视图控制器[在这种情况下 – 更新ui]对您的一个视图控制器中的操作做出反应,您尝试发布通知..这就是您在iOS中广播消息的方式

完成所需操作后,您将从视图控制器发布通知。 所有其他View控制器都会订阅该通知,并通过在发布时更新其UI来对其做出反应。

以下post快速显示发布/观察通知的示例.. https://stackoverflow.com/a/2677015/4236572

http://www.idev101.com/code/Cocoa/Notifications.html也可能会有所帮助