前言:我们数据通常是页面与页面之间的传递,但一旦需要传递的两个页面不是相邻的两个页面并且相距较远,数据的传递就稍显麻烦,以及跨组件之间的数据传递也令人头疼;所以此时使用通知就会非常方面和不受局限性
1.初始化通知Notification
通常在每个组件的定义,初始化的文件中进行初始化
/// 通知
extension Notification.Name {
struct Release {
/// 成功发布信息通知
public static let ReleaseSuccess = Notification.Name(rawValue: "ReleaseSuccess")
}
}
2.通知Notification监听
在需要收到数据,收到响应的页面进行通知的监听
ps:记得建立监听后也需要在同页面进行监听的销毁
/// 建立监听
/// selector:收到通知后会执行的操作
/// name:监听的通知名称
private func addNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(handleReleaseSuccess), name: Notification.Name.Release.ReleaseSuccess, object: nil)
}
/// 销毁监听
deinit {
NotificationCenter.default.removeObserver(self)
}
/// 收到通知后执行的操作
/// 可以通过userInfo获取到通知传递的数据
@objc
private func handleReleaseSuccess(notifi: Notification) {
///执行收到通知后的操作
if let leaseType = notifi.userInfo?["leaseType"] as? Int {
if leaseType == 1 {
pring("leaseType")
}else {
pring(leaseType)
}
}
}
3.发送通知Notification
/// 发送发布成功通知
/// 可以通过userInfo进行数据的传递,userInfo类型如同字典
NotificationCenter.default.post(name: Notification.Name.Release.ReleaseSuccess, object: nil, userInfo: ["leaseType": 1])
整理不易,如有帮助,请多多点赞收藏!谢谢大家!