在没有Segue或Programatic Call的情况下分配代表

时间:2015-12-03 17:53:58

标签: ios swift delegates protocols delegation

我需要VC3能够向VC1发送函数调用!

我理解授权的基础知识,我刚刚阅读了本指南,了解如何在没有prepareForSegue的情况下分配代理:

Swift Delegate Between Two VCs Without Segue

但是如果两者之间有一个需要谈话的VC怎么办?例如,VC1呈现VC2,其呈现VC3。 VC3希望VC1做一些工作。如果没有segue并且在VC2中发生了编程VC3调用,我该如何实现呢?

1 个答案:

答案 0 :(得分:3)

如果你想继续使用委托模式,你需要更新VC2以传递委托回调。

因此,使用您发布的示例中的代码:

<强> ViewControllerOne

class ViewControllerOne: UIViewController,testProtocol {

    @IBAction func btInit(sender: AnyObject) {
        println("Bt Init")

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController2: ViewControllerTwo = storyBoard.instantiateViewControllerWithIdentifier("viewTarget") as ViewControllerTwo
        viewController2.viewController1 = self
        self.presentViewController(initViewController,animated: false, nil)

    }

    func testDelegate(){
        println(" in my view controller delegate ")
    }

}

<强> ViewControllerTwo

class ViewControllerTwo: UIViewController,testProtocol {

    var viewController1: ViewControllerOne? = ViewControllerOne()

    @IBAction func btInit(sender: AnyObject) {
        println("Bt Init")

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController3: ViewControllerThree = storyBoard.instantiateViewControllerWithIdentifier("viewTarget") as ViewControllerThree
        viewController3.delegate = viewController1
        self.presentViewController(initViewController,animated: false, nil)

    }

}

<强> ViewControllerThree

protocol testProtocol {
    func testDelegate() // this function the first controllers
}

class ViewControllerThree: UIViewController {

    @IBAction func BtTarget(sender: AnyObject) {

        println("bt target pressed")

        delegate?.testDelegate()
    }

    var delegate : testProtocol?
}

更好的选择

就个人而言,我不喜欢这种方法,因为它在ViewControllerTwo上增加了与需要通信的其他两个VC的不必要的耦合,因此IMO更好的替代方案是通过使用{{来使用Observer模式1}}这样VC1注册为通知的监听器,然后在稍后的某个时刻,VC3发布通知(以及可选的任何数据),VC1接收它并做任何需要的事情。

相关问题