Swift初级-三种反向传值方式通知,代理,闭包
2017-02-07 本文已影响557人
镜花水月忆存逝兮
通知
第一个页面
//接受通知
let NotifMycation = NSNotification.Name(rawValue:"MyNSNotification")
NotificationCenter.default.addObserver(self, selector: #selector(upDataChange(notif:)), name: NotifMycation, object: nil)
deinit {
//移除通知
NotificationCenter.default.removeObserver(self)
}
//接收到后执行的方法
func upDataChange(notif: NSNotification) {
guard let text: String = notif.object as! String? else { return }
self.text.text = text
}
第二个页面
//发送通知
let NotifMycation = NSNotification.Name(rawValue:"MyNSNotification")
func tempbuttonAction() {
//这个方法可以传一个值
NotificationCenter.default.post(name: NotifMycation, object: self.textField.text)
//这个方法可传一个字典
// NotificationCenter.default.post(name: NotifMycation, object: nil, userInfo: ["" : ""])
self.dismiss(animated: true, completion: nil)
}
代理
第二个页面
先创建代理
protocol MyDelegate {
func didDelegateText(text: String)
}
//代理方法赋值
func tempbuttonAction() {
delegate?.didDelegateText(text: self.textField.text!)
self.dismiss(animated: true, completion: nil)
}
//第一个页面先设置代理和签协议,然后使用方法获得数据
func didDelegateText(text: String) {
self.text.text = text
}
闭包(代码块)(OC里的block)
//第二个页面
//取别名
typealias textBlock = (String) -> ()
var block: textBlock?
func getBlock(block: textBlock?) {
self.block = block
}
// MARK: - private methods(内部接口)
func tempbuttonAction() {
if let block = self.block {
block(self.textField.text!)
}
self.dismiss(animated: true, completion: nil)
}
//第一个页面
let vc = BlockViewController()
vc.getBlock{ (value) in
self.text.text = value
}
self.present(vc, animated: true, completion: nil)