How to set addObserver in SwiftUI?

前端 未结 6 2165
眼角桃花
眼角桃花 2021-02-13 16:35

How do I add NotificationCenter.default.addObserve in SwiftUI?

When I tried adding observer I get below error

Argument of \'#sele

6条回答
  •  再見小時候
    2021-02-13 17:19

    The accepted answer may work but is not really how you're supposed to do this. In SwiftUI you don't need to add an observer in that way.

    You add a publisher and it still can listen to NSNotification events triggered from non-SwiftUI parts of the app and without needing combine.

    Here as an example, a list will update when it appears and when it receives a notification, from a completed network request on another view / controller or something similar etc.

    If you need to then trigger an @objc func for some reason, you will need to create a Coordinator with UIViewControllerRepresentable

    struct YourSwiftUIView: View {
    
        let pub = NotificationCenter.default
                .publisher(for: NSNotification.Name("YourNameHere"))
    
    
        var body: some View {
            List() {
                ForEach(userData.viewModels) { viewModel in
                    SomeRow(viewModel: viewModel)
                }
            }
            .onAppear(perform: loadData)
            .onReceive(pub) { (output) in
                self.loadData()
            }
        }
    
        func loadData() {
            // do stuff
        }
    }
    

提交回复
热议问题