Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can make and put a custom Notification which fires up with changing a custom variable? (in SwiftUI or UIKit)

Tags:

swift

swiftui

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.

like image 628
ios coder Avatar asked Oct 19 '25 05:10

ios coder


1 Answers

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)
    }
}
like image 102
pawello2222 Avatar answered Oct 21 '25 18:10

pawello2222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!