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

Fer*_*yan 1 uikit swift swiftui

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

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

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

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

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

Yrb*_*Yrb 6

最简单的方法是首先创建自定义通知,如下所示:

extension Notification.Name {
    static let didPullToRefresh = Notification.Name("didPullToRefresh")
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用点符号来寻址它。接下来,在您的 VC 中:

 @objc private func fetchScheduleData(_ sender: UIRefreshControl) {
        NotificationCenter.default.post(name: .didPullToRefresh, object: nil)
    }
Run Code Online (Sandbox Code Playgroud)

最后,在您的 SwiftUI 视图中:

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

    // Do something here as a result of the notification
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

.onChange(of: watchedStateVar) { value in
    NotificationCenter.default.post(name: .didPullToRefresh, object: value)
}
Run Code Online (Sandbox Code Playgroud)