23.12.18 TIL SwiftUI 20. How to use @Binding property wrapper

Hay·2023년 12월 18일
0

SwiftUI_Beginner

목록 보기
16/19
  • @Binding을 이용해서 메인뷰와 섭뷰를 연결하기
  • 이렇게 하면 메인뷰의 변수를 섭뷰에서 사용할 수 있게된다
import SwiftUI

struct BindingBootcamp: View {
    
    @State var backgroundColor: Color = Color.green
    @State var title: String = "Title"
    
    
    var body: some View {
        ZStack {
            backgroundColor
                .ignoresSafeArea(.all)
            
            //바인딩을 하려면 $를 사용한다
            VStack {
                Text(title)
                    .foregroundStyle(.white)
                
                ButtonView(backgroundColor: $backgroundColor, title: $title)
            }
        }
    }
}


//메인뷰과 섭뷰 묶어주기
//묶지 않으면 메인뷰의 변수를 섭뷰에서는 사용할 수 없다.
struct ButtonView: View {
    
    //binding을 이용해서 메인뷰와 섭뷰 묶어주기
    @Binding var backgroundColor: Color
    //subveiw(or childview)의 변수를 만들어줄 수도 있다(메인뷰와는 무관)
    @State var buttonColor: Color = Color.blue
    //binding을 이용해서 메인뷰와 섭뷰 묶어주기
    @Binding var title: String
    
    var body: some View {
        Button(action: {
            backgroundColor = Color.orange
            buttonColor = Color.pink
            title = "New Title!!!!!".uppercased()
        }, label: {
            Text("Button")
                .foregroundStyle(.white)
                .padding()
                .padding(.horizontal)
                .background(buttonColor)
                .clipShape(.buttonBorder)
        })
    }
}

#Preview {
    BindingBootcamp()
}

0개의 댓글