← 아카이브로 돌아가기

Development · SwiftUI

@Binding으로 부모와 자식의 상태 연결하기

상태의 소유권은 부모에 두고 자식이 값을 읽고 변경하게 만드는 @Binding의 데이터 흐름을 살펴봅니다.

Velog 원문 보기 ↗

Development 아카이브 표지

자식 뷰가 부모의 상태를 바꿔야 한다고 해서 같은 값을 다시 소유하면 두 상태가 쉽게 어긋난다. @Binding은 저장 공간을 새로 만들지 않고 원래 값으로 이어지는 통로만 전달한다.

@State와 @Binding

@State에서 저장된 뷰의 상태를 다른 뷰와 공유하고 변경할 수 있게 한다. @State는 값이 변경될 때 뷰를 다시 그리고, @Binding은 값이 변경될 때 뷰 간의 데이터를 동기화한다. @Binding을 선언할 때에는 $를 붙여 사용한다.

struct BindingStudy: View { // 부모 뷰
    
    @State var backgroundColor: Color = Color.green // State 변수 선언
    
    var body: some View {
        ZStack {
            backgroundColor
                .edgesIgnoringSafeArea(.all)
            ButtonView(backgroundColor: $backgroundColor) // $를 통해 Binding

        }
    }
}

struct ButtonView: View { // 자식 뷰
    
    @Binding var backgroundColor: Color // @Binding을 통해 State 변수 Binding
    
    var body: some View {
        Button {
            backgroundColor = Color.orange // Binding된 변수 값 변경
        } label: {
            Text("Button")
                .foregroundColor(.white)
                .padding()
                .padding(.horizontal)
                .background(.blue)
                .cornerRadius(10)
        }
    }
}
← 아카이브로 돌아가기