Let's say we created a (var) variable which can be a Bool
or String
or any kind and we can change this variable with a function or button or anything you imagine. I am interested to build a notification or observation way that put's this value under magnifying glass and it is sensitive to value change of this variable.
How we can make it possible in both platform SwiftUI and UIKit?
PS: I know the usage of @State
and .onChange
, I am trying to observe with custom way.
You can create a custom notification:
extension Notification.Name {
static let customNotification = Notification.Name("customNotification")
}
And use it like this:
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)
}
}
}
You may listen to this notification wherever you want. Here is an example for a SwiftUI view:
.onReceive(NotificationCenter.default.publisher(for: .customNotification)) { notification in
if let value = notification.object as? Int {
print(value)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With