如何更好地发送完整的关闭

时间:2016-06-27 07:06:37

标签: ios swift

我想要的是将closures发送给UIViewController,告诉它最终会做什么。但是当谈到一个UIViewControllers的包时,它会有点混乱。

class ViewController: UIViewController {

    private var complete: ()->()

    init(complete: ()->()){
        self.complete = complete
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class ViewController2: UIViewController {

    private var complete: ()->()

    init(complete: ()->()){
        self.complete = complete
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

这是我的UIViewControllers。想要做的是向UIViewController2发送一个完整的闭包,但我必须首先推送UIViewController。所以我要做的是将闭包发送到UIViewController,然后UIViewController将闭包发送到UIViewController2。当只有两个UIViewControllers时,它并不凌乱。但是当出现一个UIViewControllers的包时,它会非常混乱。

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码来处理完成处理程序

首先,创建一个UIViewController的基类并定义completionHandler

ViewController1

ViewController中,您需要像这样调用另一个class ViewController: MyController { // Initialization of view objects override func viewDidLoad() { super.viewDidLoad() //You are loading another ViewController from current ViewController let controller2 = self.storyboard?.instantiateViewControllerWithIdentifier("controller2") as? MyController controller2?.onComplete({ (finished, event) in self.completionHandler?(finished, event) }) } //This is your button action or could be any event on which you will fire the completion handler @IBAction func buttonTapped() { self.completionHandler(boolType, controllerName) }

ViewController

然后,您将创建一个新的controller2?.onComplete({ (finished, event) in self.completionHandler?(finished, event) }) ,您需要通过编写行来设置其completionHandler

Xcode