SwiftUI : Passing Data to Views Seamlessly with NotificationCenter

DevTechie
DevTechie
Published in
4 min readMar 28, 2024

--

SwiftUI : Passing Data to Views Seamlessly with NotificationCenter

In previous article we learned to establish communication between views in SwiftUI.

Today, we will continue with the example and pass data to other views using NotificationCenter.

NotificationCenter’s post function facilitates communication between different parts of an app by broadcasting notifications. This function takes an optional userInfo parameter, allowing caller to attach additional data to the notification. This parameter is a dictionary containing key-value pairs, enabling the transmission of relevant information along with the notification. Utilizing this parameter, we can customize the notification’s payload, tailoring it to specific requirements. By leveraging userInfo, we can enhance the flexibility and effectiveness of NotificationCenter, enabling seamless data transfer and interaction within the app.

We will continue to build upon our example.


struct NotificationExampleView: View {
var body: some View {
NavigationStack {
VStack {
ReceiverView()
SenderView()
}
.navigationTitle("DevTechie.com")
}
}
}

struct SenderView: View {
var body: some View {

ZStack {
Color.orange.opacity(0.2)
Button("Send…

--

--