代码之家  ›  专栏  ›  技术社区  ›  swiftPunk

如何生成并放置一个自定义通知,该通知会在更改自定义变量时触发?(在SwiftUI或UIKit中)

  •  0
  • swiftPunk  · 技术社区  · 6 年前

    假设我们创建了一个(var)变量,它可以是 Bool 或 String 或者任何一种,我们可以用一个函数或者按钮或者你想象的任何东西来改变这个变量。我有兴趣建立一个通知或观察的方式,把这个值放在放大镜下,它对这个变量的值变化很敏感。

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

    附言:我知道 @State 和 .onChange

    1 回复  |  直到 6 年前
        1
  •  2
  •   pawello2222    6 年前

    您可以创建自定义通知:

    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)
        }
    }