Swift中通知中心(NotificationCenter)的使用示例
更新時間:2017年10月26日 09:41:34 作者:Mazy_ma
這篇文章主要給大家介紹了關于Swift中通知中心(NotificationCenter)使用的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。
前言
本文主要介紹了關于Swift通知中心(NotificationCenter)使用的相關內容,NotificationCenter是Swift中一個調度消息通知的類,采用單例模式設計,實現傳值、回調等作用。
通知的作用還是挺強大的,對于兩個不相關的控制器之間,要進行信息的傳遞,使用通知是個不錯的選擇,下面話不多說了,來一起看看詳細的使用方法吧。
1、添加通知
/// 通知名 let notificationName = "XMNotification" /// 自定義通知 NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name(rawValue: notificationName), object: nil)
2、設置監(jiān)聽方法
/// 接受到通知后的方法回調
@objc private func notificationAction(noti: Notification) {
/// 獲取鍵盤的位置/高度/時間間隔...
print(noti)
}
3、在通知用完后及時銷毀
/// 析構函數.類似于OC的 dealloc
deinit {
/// 移除通知
NotificationCenter.default.removeObserver(self)
}
4、發(fā)送通知
/// 發(fā)送簡單數據 NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "XMNotification"), object: "Hello 2017") /// 發(fā)送額外數據 let info = ["name":"Eric","age":21] as [String : Any] NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "XMNotification"), object: "GoodBye 2016", userInfo: info)
通知在系統中的運用,監(jiān)聽鍵盤的變動
/// 通知中心監(jiān)聽鍵盤的變化 #selector(notificationAction), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
有關鍵盤的其他通知名稱
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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
在 Swift 中測試 UIAlertController的方法
這篇文章主要介紹了在 Swift 中測試 UIAlertController的方法的,需要的朋友可以參考下2015-10-10
如何在Swift?中使用?async?let?并發(fā)運行后臺任務
Swift?異步編程是一種編寫允許某些任務并發(fā)運行而不是按順序運行的代碼的方法,這篇文章主要介紹了在Swift中使用async?let并發(fā)運行后臺任務,需要的朋友可以參考下2023-06-06

