如何在swift中更新其他控制器的UI? [英] how can i update other controllers' UI in swift?

查看:102
本文介绍了如何在swift中更新其他控制器的UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有几个控制器。当我的应用程序在一个控制器中调用一个函数时,我想更新其他控制器的UI。我怎样才能实现呢?

I have several controllers in my app. When my app call one function in one controller, I want to update other controllers' UI. How can I achieve that?

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

But FirstViewController() means I create a new FirstViewController which is I don't want, and FirstViewController has already been created. So how can I call all other controllers' updateUI() in updateAllUI()

请帮助,谢谢!

推荐答案

让视图控制器直接通信通常是一种非常糟糕的做法。我会使用 NSNotification 在视图控制器之间进行通信。通常,您的通知名称以大写字母开头,并以通知一词结尾。

It's usually a pretty bad practice to have view controllers communicate directly. I would use a NSNotification to communicate between view controllers. It's convention to have the name of your notification start with a capital letter and end with the word "Notification".

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

这篇关于如何在swift中更新其他控制器的UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆