23.12.18 TIL SwiftUI 18. Extracting functions and subviews

Hay·2023년 12월 18일
0

SwiftUI_Beginner

목록 보기
14/19
  • Etracted functions을 이용해서 View의 가독성을 높이는 방법
  • View의 일부도 var로 지정해서 body에서 사용하면 가독성이 좋아진다
import SwiftUI

struct ExtractedFunctionsBootcamp: View {
    
    //여기서 backgroundColor를 변수로 만든다
    @State var backgroundColor: Color = Color.pink
    
    var body: some View {
        ZStack {
            //background
            //여기서 backgroundColor를 사용한다
            backgroundColor
                .ignoresSafeArea(edges: .all)
            
            //content
            contentLayer

        }
    }
    
    //방법 2. We can also extract parts of view itself
    //content layer works the same as the body
    //except by default the body는 실제로 뷰에 로드되는 것
    var contentLayer: some View {
        VStack {
            Text("Title")
                .font(.largeTitle)
            Button(action: {
                //버튼 액션
                // 버튼이 눌리면 backgroundColor의 색이 바뀌는 action을 하게 한다
                buttonPressed()
                
            }, label: {
                //버튼 레이블
                Text("Press me".uppercased())
                    .font(.headline)
                    .foregroundStyle(.white)
                    .padding()
                    .background(Color.black)
                    .cornerRadius(10)
            })
            
        }
    }
    
    
    //방법 1. Extracted Function
    //View의 outside에서 펑션을 만든 뒤 사용할 수 있다
    //이렇게 view 밖에 여러개의 펑션을 새로 만들게 되면 코드를 정리할 수 있다
    //특히 버튼에 로직이 많이 쓰일때 이렇게 정리하면 좋다
    //quick tip: View의 버튼 Action에 있는 펑션 이름에 마우스 버튼 오른쪽 클릭을 하고,
    //Jump to Definition을 누르게 되면 그 펑션을 정의한/만든 곳으로 바로 이동할 수 있다
    func buttonPressed() {
        backgroundColor = .yellow
    }
     
}

#Preview {
    ExtractedFunctionsBootcamp()
}

0개의 댓글