23.12.18 TIL SwiftUI 17. How to use @State property wrapper

Hay·2023년 12월 18일
0

SwiftUI_Beginner

목록 보기
13/19

@State 를 통해서 이 variable이 바뀔 수도 있다고 View에게 알려주는 것

import SwiftUI

struct StateBootcamp: View {
    //property wrapper
    //@State -> View 에게 이 변수가 바뀔 수도 있다고 알려주는 것
    @State var backgroundColor: Color = Color.green
    @State var myTilte: String = "My Title"
    @State var count: Int = 0
    
    var body: some View {
        ZStack {
            //background layer
            backgroundColor
                .ignoresSafeArea()
            
            //content/foreground layer
            VStack(spacing: 20) {
                Text(myTilte)
                    .font(.title)
                Text("Count: \(count)")
                    .font(.headline)
                    .underline()
                HStack(spacing: 20) {
                    Button("BUTTON 1") {
                        //버튼을 클릭하면 배경색과 타이틀, 카운트가 바뀌게 된다
                        backgroundColor = .red
                        myTilte = "BUTTON 1 was pressed"
                        count += 1
                    }
                    
                    Button("BUTTON 2") {
                        backgroundColor = .purple
                        myTilte = "BUTTON 2 was pressed"
                        count -= 1
                    }
                    
                }
            }
            .foregroundStyle(.white)
        }
    }
}

#Preview {
    StateBootcamp()
}

0개의 댓글