Swift 通知实现

发通知

不带参数

NotificationCenter.default.post(name: Notification.Name("name"), object: nil)

带参数值

 NotificationCenter.default.post(name: NSNotification.Name("changeColor"), object: nil, userInfo: ["color":"green"])

接收通知

    NotificationCenter.default.addObserver(self, selector: #selector(onNotifitionClick), name: Notification.Name("name"), object: nil)
    
    NotificationCenter.default.addObserver(self, selector: #selector(onNotifitionClicks), name: Notification.Name("changeColor"), object: nil)

实现

 @objc func onNotifitionClicks(notifi : Notification) {

    print("通知实现===\(notifi)")
}
@objc func onNotifitionClick() {
    
    print("通知实现")
    self.headerView.backgroundColor = UIColor.groupTableViewBackground
}

移除通知

 deinit {
    NotificationCenter.default.removeObserver(self)
}

你可能感兴趣的:(Swift 通知实现)