一:代理
1.定义协议
protocol ContactViewDelegate:NSObjectProtocol {
// required
func setNameViewDidOnClick(name : String)
}
2.声明属性
weak var contactViewDelegate : ContactViewDelegate?
3.代理触发
self.contactViewDelegate?.setNameViewDidOnClick(name: "self")
4.在要实现的类中设置代理
let vc = testViewController()
vc.contactViewDelegate = self
5.遵循实现协议
class ViewController: UIViewController,ContactViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
func setNameViewDidOnClick(header: String) {
}
}
二:通知
- 创建发送通知
let notificationCenterKey = "notificationCenterKey"
let msg = "你有一个消息 "
NotificationCenter.default.post(name: NSNotification.Name(rawValue: notificationCenterKey), object: msg)
- 接受通知
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: notificationCenterKey), object: nil, queue: OperationQueue.main) { (notif) in
}
- 释放通知
//MARK: - 注销通知,相当于OC中的dealloc方法
deinit {
NotificationCenter.default.removeObserver(self)
}
三:闭包
- 作为属性传值
(1)定义
typealias myBlock = (_ name:String) ->Void
(2)声明属性
var myBlock: myBlock?
(3)调用
self.myBlock?("我被点击了")
(4)闭包实现
let vc = testViewController()
vc.myBlock = {(name:String) ->Void in
print(name)
}
- 作为方法参数
(1)定义方法
func loadRequest(callBack:(_ name: String) -> Void) {
callBack("哈low我")
}
(2)调用
loadRequest { (name) in
print(name)//哈low我
}