如何在SwiftUI中设置addObserver?

如何在SwiftUI中添加 NotificationCenter.default.addObserve

当我尝试添加观察者时,出现错误

  

“#selector”的参数引用实例方法“ VPNDidChangeStatus”   没有暴露于Objective-C

但是当我在func前面添加 @objc 时,我得到以下错误

  

@objc只能与类成员,@ objc协议和   类的具体扩展

这是我的代码

let NC = NotificationCenter.default

var body: some View {
     VStack() {

     }.onAppear {

           self.NC.addobserver(self,selector: #selector(self.VPNDidChangeStatus),name: .NEVPNStatusDidChange,object: nil)

     }
} 

@objc func VPNDidChangeStatus(_ notification: Notification) {
    //    print("VPNDidChangeStatus",VPnmanager.shared.status)
}
syz12589 回答:如何在SwiftUI中设置addObserver?

可接受的答案可能有效,但实际上并不是您应该如何执行。在SwiftUI中,您不需要以这种方式添加观察者。

您添加了一个发布者,它仍然可以侦听从应用程序的非SwiftUI部分触发的NSNotification事件,而无需合并。

在此,列表将在另一个视图/控制器或类似的对象上完成的网络请求中出现时,在收到通知时更新。

如果由于某种原因然后需要触发@objc函数,则需要使用Coordinator创建一个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
    }
}
,

我在NotificationCenter中有一种使用SwiftUI的方法。

有关更多信息,Apple Documentation

通知范围 n

extension NSNotification {
    static let ImageClick = NSNotification.Name.init("ImageClick")
}

ContentView

struct ContentView: View {
    var body: some View {
        VStack {
            DetailView()
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.ImageClick))
        { obj in
           // Change key as per your "userInfo"
            if let userInfo = obj.userInfo,let info = userInfo["info"] {
              print(info)
           }
        }
    }
}

DetailView

struct DetailView: View {
    var body: some View {
        Image(systemName: "wifi")
            .frame(width: 30,height: 30,alignment: .center)
            .foregroundColor(AppColor.black)
            .onTapGesture {
                NotificationCenter.default.post(name: NSNotification.ImageClick,object: nil,userInfo: ["info": "Test"])
        }
    }
}
,

这不是SwiftUI原生方法,而是声明式和响应式的。相反,您应该使用Combine的NSNotificationCenter.publisher(for:object:)。

Apple Documentation

中查看更多详细信息 ,

我使用此扩展程序,因此在呼叫站点上会更好一些:

/// Extension

extension View {
    func onReceive(_ name: Notification.Name,center: NotificationCenter = .default,object: AnyObject? = nil,perform action: @escaping (Notification) -> Void) -> some View {
        self.onReceive(
            center.publisher(for: name,object: object),perform: action
        )
    }
}

/// Usage

struct MyView: View {
    var body: some View {
        Color.orange
            .onReceive(.myNotification) { _ in
                print(#function)
            }
    }
}

extension Notification.Name {
    static let myNotification = Notification.Name("myNotification")
}

,

交换此

self.NC.addObserver(self,selector: #selector(self.VPNDidChangeStatus),name: .NEVPNStatusDidChange,object: nil) 

self.NC.addObserver(self,selector: #selector(VPNDidChangeStatus(_:)),object: nil)
,

这对我有用

   let NC = NotificationCenter.default



   self.NC.addObserver(forName: .NEVPNStatusDidChange,queue: nil,using: self.VPNDidChangeStatus)


   func VPNDidChangeStatus(_ notification: Notification) {


    }
本文链接:https://www.f2er.com/3117703.html

大家都在问