我们如何制作和放置自定义通知,该通知随更改自定义变量而启动? (在SwiftUI或UIKit中)

时间:2020-10-18 22:32:25

标签: swift swiftui

假设我们创建了一个(var)变量,它可以是BoolString或任何类型,我们可以使用函数或按钮或您想象的任何方式更改此变量。我有兴趣构建一种通知或观察方式,将该值放在放大镜下,并且对此变量的值更改敏感。

我们如何在平台SwiftUI和UIKit中实现这一目标?

PS:我知道@State.onChange的用法,我正在尝试以自定义方式进行观察。

1 个答案:

答案 0 :(得分:2)

您可以创建自定义通知:

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

并像这样使用它:

struct ContentView: View {
    @State var test = 0
    
    var body: some View {
        Button("Increment") {
            test += 1
        }
        .onChange(of: test) { value in
            NotificationCenter.default.post(name: .customNotification, object: value)
        }
    }
}

您可以随时随地收听此通知。这是一个SwiftUI视图的示例:

.onReceive(NotificationCenter.default.publisher(for: .customNotification)) { notification in
    if let value = notification.object as? Int {
        print(value)
    }
}