委派多个视图控制器

时间:2017-07-26 10:04:51

标签: ios swift cocoa

我有主视图控制器,它连接到2个视图控制器。 我制作了协议,其中我有didRecive(data:Data)委托函数。

protocol MainViewControllerDelegate: class {
func didReciveDepartment(response:DepartmentResponse)

}

在主视图控制器中,我声明了委托变量

    weak var delegate: DepartmentMainViewControllerDelegate?

在准备segue时,我将此委托设置为viewCotnroller' s。像这样 -

        if segue.identifier == "productsEmbedded" {
        let vc = segue.destination as! DepartmentProductsViewController
        delegate = vc


    }
    if segue.identifier == "shopsEmbedded" {
        let vc = segue.destination as! DepartmentShopsViewController
        vc.delegate = self
        delegate = vc
    }

我在DepartmentShopsViewController中只有有线行为委托触发器,而且DepartmentProductsViewController无法获得此委托,我评论了商店和产品得到了这个delgate所以这意味着我不能为2个控制器使用相同的委托?

3 个答案:

答案 0 :(得分:2)

这些是在对象之间传递消息的多种方法。您可以使用Delegate并使用NSNotificationCentre传递数据。主要区别在于代表,一个指定对象接收消息,wheras 任何数量的对象在发布时都可以收到通知。 您可以查看this之前的SO问题以获取详细信息。

答案 1 :(得分:0)

来吧,你忘了一条线

    vc.delegate = self        

代码应如下所示

if segue.identifier == "productsEmbedded" {
    let vc = segue.destination as! DepartmentProductsViewController
    vc.delegate = self     //Add this Line   
    delegate = vc
}
if segue.identifier == "shopsEmbedded" {
    let vc = segue.destination as! DepartmentShopsViewController
    vc.delegate = self
    delegate = vc
}

答案 2 :(得分:0)

对于Delegate,你必须像那样实现

//Declare protocol
protocol MainViewControllerDelegate {
    func didReciveDepartment(response:DepartmentResponse)
}

class DepartmentProductsViewController: UIViewController {

    // MARK: - Variable Declaration.
    var delegate: MainViewControllerDelegate?

}

class DepartmentShopsViewController: UIViewController {

    // MARK: - Variable Declaration.
    var delegate: MainViewControllerDelegate?

}

class  MainViewController: UIViewController, MainViewControllerDelegate {

    //Push ViewController with segue and  use delegate property
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "productsEmbedded"{

            let vc = segue.destination as! DepartmentProductsViewController
            vc.delegate = self
        } else if segue.identifier == "shopsEmbedded" {

            let vc = segue.destination as! DepartmentShopsViewController
            vc.delegate = self
        }
    }

    //MARK: Implement MainViewControllerDelegate Methods.
    func didReciveDepartment(response: DepartmentResponse) {

    }

}