NotificationCenter是Swift中一個調度消息通知的類,采用單例模式設計,實現傳值、回調等作用.通知的作用還是挺強大的,對於兩個不相關的控制器之間,要進行信息的傳遞,使用通知是個不錯的選擇.
1、添加通知
/// 通知名 let notificationName = "LXNotification" /// 自定義通知 NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name(rawValue: notificationName), object: nil)
2、設置監聽方法
/// 接受到通知后的方法回調 @objc private func notificationAction(noti: Notification) { /// 獲取鍵盤的位置/高度/時間間隔... print(noti) }
3、在通知用完后及時銷毀
/// 析構函數.類似於OC的 dealloc deinit { /// 移除通知 NotificationCenter.default.removeObserver(self) }
4、發送通知
/// 發送簡單數據 NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "LXNotification"), object: "Hello 2017") /// 發送額外數據 let info = ["name":"Eric","age":21] as [String : Any] NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "LXNotification"), object: "GoodBye 2016", userInfo: info)
通知在系統中的運用,監聽鍵盤的變動
/// 通知中心監聽鍵盤的變化 #selector(notificationAction), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
5.有關鍵盤的其他通知名稱
public static let UIKeyboardWillShow: NSNotification.Name /// 鍵盤顯示完畢 public static let UIKeyboardDidShow: NSNotification.Name /// 鍵盤將要隱藏 public static let UIKeyboardWillHide: NSNotification.Name /// 鍵盤隱藏完畢 public static let UIKeyboardDidHide: NSNotification.Name /// 鍵盤將要改變自身的frame public static let UIKeyboardWillChangeFrame: NSNotification.Name /// 鍵盤frame改變完成 public static let UIKeyboardDidChangeFrame: NSNotification.Name