SwiftUI : Leveraging Notifications for Seamless Communication Between Views
Notifications in iOS allow different parts of an app to talk to each other without being directly connected. Using something called NotificationCenter
, one part of the app can send out a message (notification) to other parts that are interested. These other parts can then react to the message without having to know exactly where it came from. This makes the app easier to manage and change because each part can work independently. iOS notifications help keep the app organized, make it easier to add new features, and ensure that everything responds quickly to what the user does.
To understand this better, let’s create two views that don’t share any common model, yet can communicate with each other using notifications.
The first view is the notification receiver view, which consists of a @State
property named counter
initialized to 0 to indicate the number of received notifications. It also includes a ZStack
to layer a semi-transparent mint-colored background and a Text
view displaying the number of notifications received.
struct ReceiverView: View {
@State private var counter = 0
var body: some View {
ZStack {
Color.mint.opacity(0.2)
Text("Received **\(counter)** notifications.")
}
}
}