通知

常用的系统通知:

// 监听文本文字改变事件  NSNotification.Name.UITextViewTextDidChange

// 监听键盘弹出  NSNotification.Name.UIKeyboardWillChangeFrame

// 键盘的frame  let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).cgRectValue

// 键盘的动画时长  let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue

发送与注册通知示例代码:

 1         // 发送自定义通知,通知名:NSNotification.Name("customNotificationName")
 2         NotificationCenter.default.post(name: NSNotification.Name("customNotificationName"), object: nil, userInfo: nil)
 3         
 4         // 注册自定义通知:通知名:NSNotification.Name("customNotificationName")
 5         NotificationCenter.default.addObserver(self, selector: #selector(customNotificationAction(noti:)), name: NSNotification.Name("customNotificationName"), object: nil)
 6         
 7         // 发送系统通知,通知名:NSNotification.Name.UITextViewTextDidChange
 8         NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil, userInfo: nil)
 9         
10         // 注册系统通知:通知名:NSNotification.Name.UITextViewTextDidChange
11         NotificationCenter.default.addObserver(self, selector: #selector(textChange(noti:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil)

通知对应的事件处理与移除:

 1     @objc private func textChange(noti:Notification){
 2         // noti.object:
 3         // noti.userInfo:都能做为参数传递
 4     }
 5     
 6     @objc private func customNotificationAction(noti:Notification){
 7         // noti.object:
 8         // noti.userInfo:都能做为参数传递
 9     }
10 
11     // 移除通知
12     deinit {
13         NotificationCenter.default.removeObserver(self)
14     }

 注意:如果使用闭包的方式注册通知,会有一些注意点:

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4     
 5     // 记录当前的观察者对象
 6     var observer:NSObjectProtocol?
 7     
 8     override func viewDidLoad() {
 9         super.viewDidLoad()
10         
11         //  forName: 通知名
12         //  object: 表示监听哪个对象发送过来的通知,如果传nil,那么监听所有对象发送的通知
13         //  queue: 表示这个通知的的闭包或者block在哪个队列上执行 , 如果传入nil, 表示使用当前的队列调用闭包或者block
14         //  using: 监听的通知方法
15         //  闭包会持有我们的当前对象 -> 循环引用问题;解包办法 -> [weak self] -> 解决循环引用的问题
16         //  移除观察者的问题不是当前对象self -> 通知还能监听;解决办法-> 移除指定的观察者对象
17         observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("customNotificationName"), object: nil, queue: nil) { [weak self](noti) in
18             
19             print(self ?? "执行通知闭包")
20             
21         }
22         
23     }
24     
25     deinit {
26         // xcode不会判断, 自己需要解包
27         NotificationCenter.default.removeObserver(observer!)
28         print("over")
29     }
30     
31     // 其他页面发送通知,可以发现,必须记录观察者对象,才能移除通知
32     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
33         NotificationCenter.default.post(name: NSNotification.Name("customNotificationName"), object: nil)
34     }
35 }
原文地址:https://www.cnblogs.com/panda1024/p/6216853.html