我想要的是将 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/