如何使用闭包在两个ViewController之间传递数据 [英] How to pass data between two ViewController using closure
本文介绍了如何使用闭包在两个ViewController之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何使用闭包传递数据。我知道数据传递方法有三种:
I want to know how to pass data using closure. I know that there are three types of data pass approaches:
-
委托
delegate
通知中心
关闭
我想用一个例子来适当地说明闭包。
I want proper clarification of closure with an example.
推荐答案
很好地传递带有块/闭包的数据并且合理的方法,比通知更好。
下面是相同的代码。
Well passing data with blocks / closures is a good and reasonable approach and much better than notifications. Below is the same code for it.
第一个ViewController(在其中创建第二个ViewController的对象)
@IBAction func push(sender: UIButton) {
let v2Obj = storyboard?.instantiateViewControllerWithIdentifier("v2ViewController") as! v2ViewController
v2Obj.completionBlock = {[weak self] dataReturned in
//Data is returned **Do anything with it **
print(dataReturned)
}
navigationController?.pushViewController(v2Obj, animated: true)
}
第二个ViewController(将数据传递回First VC)
import UIKit
typealias v2CB = (infoToReturn :String) ->()
class v2ViewController: UIViewController {
var completionBlock:v2CB?
override func viewDidLoad() {
super.viewDidLoad()
}
func returnFirstValue(sender: UIButton) {
guard let cb = completionBlock else {return}
cb(infoToReturn: "any value")
}
}
这篇关于如何使用闭包在两个ViewController之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文