← Back to archive

Development · SwiftUI

Connecting parent and child state with @Binding

Let a child read and update a value while its parent remains the source of truth.

Read the Korean original on Velog ↗English translation

Development archive cover

Giving a child a second copy of its parent's state can cause the two values to drift apart. A binding provides access to the original value without creating another storage location.

@State and @Binding

The parent owns its value with @State. The child receives a @Binding so it can read and write that same value. Pass the projected binding with the $ prefix, such as $isOn, rather than passing the value alone.

struct BindingStudy: View { // Parent view
    
    @State var backgroundColor: Color = Color.green // Declare state
    
    var body: some View {
        ZStack {
            backgroundColor
                .edgesIgnoringSafeArea(.all)
            ButtonView(backgroundColor: $backgroundColor) // Pass a binding with $

        }
    }
}

struct ButtonView: View { // Child view
    
    @Binding var backgroundColor: Color // Bind to the state with @Binding
    
    var body: some View {
        Button {
            backgroundColor = Color.orange // Update the bound value
        } label: {
            Text("Button")
                .foregroundColor(.white)
                .padding()
                .padding(.horizontal)
                .background(.blue)
                .cornerRadius(10)
        }
    }
}
← Back to archive