Send state variable data to a child view in SwiftUI
In this tutorial, we will learn how to send state variable data from a parent view to a child view in SwiftUI.
In SwiftUI app development transferring data from a parent view to a child view is a common requirement, especially state variable values.
SwiftUI provides a convenient way to manage state within views using @State and allows us to share this state between views using @Binding.
Now, follow the steps below to achieve this task.
Create a parent view
First of all, I will create a parent view called ContentView which will be our main view. Within this view, I will declare a state variable using the @State property wrapper. This variable will hold the data that we want to send to the child view.
Example
struct ContentView: View {
// State variable to hold the message in the parent view
@State private var message = "Hello from Parent View!"
var body: some View {
// Calling the ChildView and passing the message using Binding
ChildView(message: $message)
}
}In the above program, I have declared a mutable state variable called message using the @State property wrapper. This variable holds the message that we want to display.
Then, in the body of the ContentView, I have called ChildView and passed a binding ($message) to the message state variable. This means that any changes made to message within ChildView will affect the original message state in ContentView.
Create the Child View with @Binding
Now, I will create the child view (ChildView) and within this child view I will declare a @Binding variable. The @Binding is another property wrapper provided by SwiftUI that creates a two-way connection between a parent and a child view.
Example
struct ChildView: View {
// Binding variable to hold the reference to the message from the parent view
@Binding var message: String
var body: some View {
// Displaying the text using the message received from the parent view
Text(message)
}
}In the above code, I have declared a binding variable called message using the @Binding property wrapper. This binding is used to create two-way connection with the message variable in the parent view. It will allow the child view to read and write to the message variable from the parent view.
Then, I have created a Text view to display the content of the message received from the parent view.
Have a look at the complete code below.
import SwiftUI
struct ContentView: View {
// State variable to hold the message in the parent view
@State private var message = "Hello from Parent View!"
var body: some View {
ChildView(message: $message)
}
}
struct ChildView: View {
// Binding variable to hold the reference to the message from the parent view
@Binding var message: String
var body: some View {
Text(message)
}
}Output:

You may also read Update parent view from child in SwiftUI
Leave a Reply