可接受的答案可能有效,但实际上并不是您应该如何执行。在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