闭包 –> 逆向传值
SecondViewController控制器
import UIKit
class SecondViewController: UIViewController {
import UIKit
class SecondViewController: UIViewController {
// ***** 注意 *****
// 声明闭包的时候 必须对闭包进行初始化 = {} 否则闭包会一直为nil, callBack类型为元组,参数传递,可以拼接类型(Int, String,...), 取值的时候根据元组获取值value.0, value.1,....
var callBack:((Int)->())? = {
value in
};
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let btn = UIButton()
btn.setTitle("返回", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btn.backgroundColor = UIColor.purple
btn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
self.view.addSubview(btn)
}
func backBtnClick() {
if self.callBack != nil { // 判断闭包不为空的时候将值传递出去
self.callBack!(123);
self.navigationController?.popViewController(animated: true)
}
}
}
FirstViewController控制器
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let btn = UIButton()
btn.setTitle("跳转", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btn.backgroundColor = UIColor.purple
btn.addTarget(self, action: #selector(pushBtnClick), for: .touchUpInside)
self.view.addSubview(btn)
}
func pushBtnClick() {
let secondVC = SecondViewController()
secondVC.callBack = { // 获取call回来的值
value in
print(value,"value....")
}
self.navigationController?.pushViewController(secondVC, animated: true)
}
}