我们如何将闭包传递给应用程序流中的任何ViewController? [英] How can we pass the closures to any ViewController in the app flow?
问题描述
在View Controller A中,
In View Controller A,
var completionBlock: (((String) -> ()))? = nil
&我将完成块称为(ViewController A):
& I am calling the completion block like(ViewController A):
if let block = completionBlock {
block("block data to pass")
}
我不想将完成数据传递给ViewController B,相反,我想传递给从ViewController B呈现的ViewController C.
I don't want to pass the completion data to ViewController B, instead i want to pass to ViewController C which is presenting from ViewController B.
简单地说,我想将闭包数据从ViewController A传递到ViewController C.我知道如何通过委托传递数据,只是对闭包感到好奇?
In simple words, i want to pass the closure data to from ViewController A to ViewController C.I know how to pass data with delegates, just curious with closures?
我们如何实现?
推荐答案
这只是我为您快速编写的示例代码,您可以根据需要修改对象.希望能解决您的问题.
This is just a sample code i quickly wrote for you, you can modify objects based on your need. Hopefully will address your problem.
import UIKit
class ViewControllerA: UIViewController {
var block:(((String) -> ()))? = { input in
print(input)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "A"
let VCB = ViewControllerB()
let VCC = ViewControllerC()
VCC.block = block
VCB.VCC = VCC
self.navigationController?.pushViewController(VCB, animated: true)
}
}
class ViewControllerB: UIViewController {
var VCC:ViewControllerC?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let VCC = VCC {
self.present(VCC, animated: true, completion: nil)
}
}
}
class ViewControllerC: UIViewController {
var block:(((String) -> ()))? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .yellow
//Will run the block that has been passed
block?("test")
}
}
这篇关于我们如何将闭包传递给应用程序流中的任何ViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!