前言
本文主要介紹了關于Swift通知中心(NotificationCenter)使用的相關內容,NotificationCenter是Swift中一個調度消息通知的類,采用單例模式設計,實現傳值、回調等作用。
通知的作用還是挺強大的,對于兩個不相關的控制器之間,要進行信息的傳遞,使用通知是個不錯的選擇,下面話不多說了,來一起看看詳細的使用方法吧。
1、添加通知
1
2
3
4
|
/// 通知名 let notificationName = "XMNotification" /// 自定義通知 NotificationCenter. default .addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name(rawValue: notificationName), object: nil) |
2、設置監聽方法
1
2
3
4
5
|
/// 接受到通知后的方法回調 @objc private func notificationAction(noti: Notification) { /// 獲取鍵盤的位置/高度/時間間隔... print(noti) } |
3、在通知用完后及時銷毀
1
2
3
4
5
|
/// 析構函數.類似于OC的 dealloc deinit { /// 移除通知 NotificationCenter. default .removeObserver(self) } |
4、發送通知
1
2
3
4
5
6
|
/// 發送簡單數據 NotificationCenter. default .post(name: NSNotification.Name.init(rawValue: "XMNotification" ), object: "Hello 2017" ) /// 發送額外數據 let info = [ "name" : "Eric" , "age" :21] as [String : Any] NotificationCenter. default .post(name: NSNotification.Name.init(rawValue: "XMNotification" ), object: "GoodBye 2016" , userInfo: info) |
通知在系統中的運用,監聽鍵盤的變動
1
2
|
/// 通知中心監聽鍵盤的變化 #selector(notificationAction), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) |
有關鍵盤的其他通知名稱
1
2
3
4
5
6
7
8
9
10
11
|
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 |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://blog.csdn.net/mazy_ma/article/details/54409837