我有一个视图,在其中添加观察者onAppear并在onDisappear方法中删除该观察者。但观察者并没有被移除。我阅读了文档但没有找到任何解决方案。寻求帮助。谢谢
struct MainListView: View {
let NC = NotificationCenter.default
var body: some View {
VStack(alignment: .center, spacing: 1) {
.......
}
.onDisappear{
self.NC.removeObserver(self, name: Notification.Name(rawValue: "redrawCategories"), object: self)
}
.onAppear {
self.NC.addObserver(forName: Notification.Name(rawValue: "redrawCategories"), object: nil, queue: nil) { (notification) in
.......
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是观察通知的 SwiftUI 方法
struct MainListView: View {
let redrawCategoriesPublisher = NotificationCenter.default.publisher(for:
Notification.Name(rawValue: "redrawCategories"))
var body: some View {
VStack(alignment: .center, spacing: 1) {
Text("Demo")
}
.onReceive(redrawCategoriesPublisher) { notification in
// do here what is needed
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1864 次 |
| 最近记录: |