0%

Swift闭包(Closure)回调传值

Swift闭包(Closure)回调传值

场景:

A页面present到B页面,B页面dismiss到A页面时,把值传递给A页面

1. 在B页面定义一个闭包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import UIKit

// 定义一个闭包类型
typealias callBackCompletion = (_ str: String, _ age: Int) -> Void

class NextViewController: UIViewController {
// 定义一个变量,把闭包当变量使用
fileprivate var callBack: callBackCompletion?
private var name: String?
private var age: Int?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.callBack != nil {
self.callBack!(self.name! + "11", self.age! + 22)
self.dismiss(animated: true, completion: nil)
}
}

// MARK: - 回调函数
func setCallBackValue(name: String, age: Int, callBack: @escaping callBackCompletion) {
self.name = name
self.age = age
self.callBack = callBack
}
}

2.在A页面得到值

1
2
3
4
5
6
7
 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let vc = NextViewController()
vc.setCallBackValue(name: "Ghost", age: 20) { (name, age) in
print("\(name, age)")
}
self.present(vc, animated: true, completion: nil)
}