IOS Swift5.5的通知写法
生活随笔
收集整理的這篇文章主要介紹了
IOS Swift5.5的通知写法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
IOS Swift5.5的通知寫法
新建一個Common.swift 文件,把默認的全部刪掉。里面書寫通知的名字:
import UIKit let kWBAppearanceTintColor: UIColor = UIColor.orange extension NSNotification.Name {static let ktypeChangeNotification = NSNotification.Name("typeChangeNotification") }仿照上面寫,見名知意。通知一般前面加k,后面加Notification,不要亂起名字。
二。在你需要發送通知的地方書寫:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {let type = typeMs[indexPath.row]NotificationCenter.default.post(name: .ktypeChangeNotification, object: type, userInfo: nil)// NotificationCenter.default.post(name: .ktypeChangeNotification, object: type)}name 直接通過點語法,直接去點你Common文件的全局通知名稱。object是你對外傳輸的參數,userInfo可以為空。
三,在其他控制器去接收通知,或者叫注冊通知,重點掌握swift的#selector參數傳參的寫法。
override func viewDidLoad() {super.viewDidLoad()NotificationCenter.default.addObserver(self, selector: #selector(typeChange(noti:)), name: .ktypeChangeNotification, object: nil)}@objc func typeChange(noti: Notification) -> Void {debugPrint(noti)}還有函數一般加@objc,為了更加嚴謹。
四。銷毀通知
在你注冊通知的控制器務必寫銷毀通知,不然有問題.
deinit{//注銷通知NotificationCenter.default.removeObserver(self, name: .ktypeChangeNotification, object: nil)}在deinit函數里面寫,繼續使用點語法,把通知的名字拿到。
總結
以上是生活随笔為你收集整理的IOS Swift5.5的通知写法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 养心灵,才能美容颜,拥有好日子(图)
- 下一篇: 路考口诀