개인공부

SwiftUI _ @State, @Binding

h_luz 2024. 7. 22. 16:52

@State

: 뷰에게 변수의 상태를 관찰하라고 지시

 

import SwiftUI

struct StatePractice: View {
    
    //@State : 뷰에게 변수의 상태를 관찰하라고 지시
    @State var backgroundColor: Color = Color.green
    @State var myTitle: String = "Title"
    @State var count: Int = 0
    
    var body: some View {
        ZStack {
            backgroundColor
                .ignoresSafeArea()
            VStack(spacing: 20) {
                Text(myTitle)
                    .font(.title)
                Text("Count: \(count)")
                    .font(.headline)
                    .underline()
                
                HStack(spacing: 20) {
                    Button("Button 1") {
                        backgroundColor = .yellow
                        myTitle = "Button1 was pressed"
                        count += 1
                    }
                    
                    Button("Button 2") {
                        backgroundColor = .red
                        myTitle = "Button2 was pressed"
                        count -= 1
                    }
                }
            }
        }
    }
}

#Preview {
    StatePractice()
}

 


 

@Binding

: 다른 뷰에서 State로 선언된 상태변수를 사용하려고 하는 경우 사용

  즉, 하위 뷰의 변수를 상위 뷰에서 선언된 상태 변수에 연결하는 역할

 

import SwiftUI

struct BindingPractice: View {
    
    @State var backgroundColor: Color = Color.green
    @State var title:String = "Title"
    
    var body: some View {
        ZStack {
            backgroundColor
                .ignoresSafeArea()
            
            VStack {
                Text(title)
                    .foregroundStyle(.white)
                
                ButtonView(backgroundColor: $backgroundColor, title: $title)
            }
        }
    }
}

struct ButtonView: View {
    
    // @Binding : 다른 뷰에서 State로 선언된 상태변수를 사용하려고 하는 경우 사용
    // 즉, 하위 뷰의 변수를 상위 뷰에서 선언된 상태 변수에 연결하는 역할
    @Binding var backgroundColor: Color
    @State var buttonColor: Color = Color.yellow
    
    @Binding var title: String
    
    var body: some View {
        Button(action: {
            backgroundColor = Color.blue
            buttonColor = Color.green
            title = "New Title"
        }, label: {
            Text("Button")
                .foregroundStyle(.white)
                .padding()
                .padding(.horizontal)
                .background(buttonColor)
                .cornerRadius(10.0)
        })
    }
}

#Preview {
    BindingPractice()
}