ios - 如何更好地发送完整的闭包

标签 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出来就很乱了。

有更好的解决方案吗?

最佳答案

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

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

import UIKit

public class MyController: UIViewController {

var completionHandler: ((Bool, String) -> Void)? // Bool and String are the return type, you can choose anything you want to return

public func onComplete(completion : ((Bool, String) -> Void)?)
{
    self.completionHandler = completion
}

override public func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

override public func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

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,您需要通过编写以下行来设置它的 completionHandler

controller2?.onComplete({ (finished, event) in
    self.completionHandler?(finished, event)
}) 

关于ios - 如何更好地发送完整的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38047790/

相关文章:

swift - 如何隐藏单元格的开关?

macos - 如何在 Swift 中单击按钮时填充 NSTableView

json - 如何使用 Swift 格式化 JSON 日期字符串?

ios - 无法在iOS中使用swift解析json

ios - 自动布局停止 UITapGestureRecognizer?

ios - 检索用户的关注者的谓词

ios - 展开字典项值

swift - Swift 中 'get' 和 'get set' 的区别

android - 有没有办法在复制内容时获取网址、作者姓名和网页的其他详细信息(Android 和 iOS)

ios - 确保属性观察者 didSet 在 vi​​ewDidLoad 之后操作用户界面