@Binding lets a child view read and write a value owned by its parent. This helps keep data in sync between views.
0
0
@Binding for child communication in iOS Swift
Introduction
When a parent view owns some data but a child view needs to update it.
When you want to share state between views without duplicating it.
When building forms where child inputs change parent data.
When you want a child view to control a toggle or slider that affects parent state.
Syntax
iOS Swift
struct ChildView: View {
@Binding var isOn: Bool
var body: some View {
Toggle("Switch", isOn: $isOn)
}
}Use @Binding in the child to declare a variable that links to the parent's state.
Pass the binding from the parent using the $ prefix.
Examples
The parent owns the
isOn state and passes a binding to the child.iOS Swift
struct ParentView: View {
@State private var isOn = false
var body: some View {
ChildView(isOn: $isOn)
}
}The child can modify the parent's
count state through the binding.iOS Swift
struct ChildView: View {
@Binding var count: Int
var body: some View {
Button("Increment") {
count += 1
}
}
}Sample App
This app shows a toggle switch controlled by the child view. The parent displays the current state text. Changing the toggle updates the parent's state instantly.
iOS Swift
import SwiftUI struct ParentView: View { @State private var isOn = false var body: some View { VStack { Text(isOn ? "Switch is ON" : "Switch is OFF") .font(.title) .padding() ChildView(isOn: $isOn) .padding() } } } struct ChildView: View { @Binding var isOn: Bool var body: some View { Toggle("Toggle Switch", isOn: $isOn) .padding() } } struct ContentView: View { var body: some View { ParentView() } }
OutputSuccess
Important Notes
Always prefix the parent's state with $ when passing to a @Binding variable.
Bindings keep data in sync both ways: child changes update parent and parent changes update child.
Use @State in the parent and @Binding in the child for this pattern.
Summary
@Binding lets child views read and write parent state.
Pass bindings from parent to child using $ prefix.
This keeps data synchronized between views easily.