用代理和闭包进行逆向传值
闭包
-
在第二个页面写一个闭包(要传的值是字符串, 整型, 字典)
typealias InputClosureType = (String, Int, [String: String]) -> Void
-
需要在第二个页面理创建一个闭包
var backClosure: InputClosureType?
-
在点击事件里执行闭包
if self.backClosure != nil { self.backClosure?("卢梦如", 24, ["name": "卢梦如"]) }
-
在第一个页面里创建第二个页面的实例的地方对闭包传值
secondVC.backClosure = { (name: String, age: Int, dictionary: [String: String]) -> Void in // 打印传过来的数据 print("\(name) is \(age) years", dictionary) }
代理
-
在第二个页面里 声明一个代理
protocol SecondViewControllerDelegate: NSObjectProtocol { func backValue(string: String, value: Int) }
-
定义代理
var delegate: SecondViewControllerDelegate?
-
在点击事件里执行代理
if self.delegate != nil { delegate?.backValue(string: "卢梦如", value: 24) }
-
在第一个页面里面遵守代理, 然后设置代理
secondVC.delegate = self
-
执行代理的方法
func backValue(string: String, value: Int) { // 打印传入的数据 print("\(string) is \(value)") }