假设我们创建了一个 (var) 变量,它可以是 Bool
或 String
或任何类型,我们可以用函数或按钮或任何你想要的东西来改变这个变量想象。我有兴趣建立一个通知或观察方式,将这个值放在放大镜下,并且它对这个变量的值变化很敏感。
我们如何在 SwiftUI 和 UIKit 平台上实现它?
PS:我知道@State
和.onChange
的用法,我想用自定义的方式观察。
最佳答案
您可以创建自定义通知:
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 View 的示例:
.onReceive(NotificationCenter.default.publisher(for: .customNotification)) { notification in
if let value = notification.object as? Int {
print(value)
}
}
关于swift - 我们如何制作和放置一个自定义通知,它会随着更改自定义变量而启动? (在 SwiftUI 或 UIKit 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64418971/