如何将通知从 UIKit 发送到 SwiftUI 中的视图?

How to send a notification from UIKit to a view in SwiftUI?

我正在尝试在用户拉动刷新后从 UIViewcontroller 向 SwiftUI View 发送通知。

 @objc private func fetchScheduleData(_ sender: UIRefreshControl) {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "didPullToRefreash"), object: nil)
     
    }

在 SwiftUI 视图上,我尝试设置此方法 .onchange()

   NotificationCenter.default.addObserver(self, selector: #selector(didPullToRefreashHelper), name: Notification.Name(rawValue: "didTapNotification"), object: nil)

但是 onChange 不起作用。我想知道我将如何做到这一点。

最简单的方法是首先像这样创建自定义通知:

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

现在您可以使用点符号来解决它。接下来,在您的 VC:

 @objc private func fetchScheduleData(_ sender: UIRefreshControl) {
        NotificationCenter.default.post(name: .didPullToRefreash, object: nil)
    }

最后,在您的 SwiftUI 视图中:

.onReceive(NotificationCenter.default.publisher(for: .didPullToRefreash)) { _ in
    // If you are passing an object, this can be "notification in"

    // Do something here as a result of the notification
}

编辑:

如果您想在变量更改时在 SwiftUI 视图中发送消息,那么您可以像这样使用 .onChange(of:)

.onChange(of: watchedStateVar) { value in
    NotificationCenter.default.post(name: .didPullToRefreash, object: value)
}