23.12.18 TIL SwiftUI 19. How to Extract Subviews

Hay·2023년 12월 18일
0

SwiftUI_Beginner

목록 보기
15/19
  • subview를 이용해서 body를 더 깔끔하게 작성하는 법
  • dynamic과 static - 값이 바뀔때랑 바뀌지 않을떄
  • 블록하고나서 마우스 오른쪽 클릭하면 이런 창이 뜬다
    • 여기서 Extract Subview를 누르면 된다
import SwiftUI

struct ExtractSubviewsBootcamp: View {
    var body: some View {
        ZStack {
            Color(#colorLiteral(red: 0.4513868093, green: 0.9930960536, blue: 1, alpha: 1)).ignoresSafeArea(.all)
            
            //subview를 extract 하는 법 1
            //여기에 있던 VStack에 마우스 오른쪽 클릭 후, Extract Subview를 누르면
            //이렇게 아래와 같이 알아서 나누어(?)진다.
            //so this is more dynamic.(than 지난 강의에서 연습한것)
            //cuz we can now reuse this item and we can change the inputs.
            HStack { //이렇게 써서 여러개의 MyItem을 만들 수 있다. 
                MyItem(title: "Apples", count: 1, color: .red)
                MyItem(title: "Oranges", count: 10, color: .orange)
                MyItem(title: "Bananas", count: 34, color: .yellow)
            }
        }
        /*
         //마지막 정리.
         //위의 HStack을 여기에 쓰고, 위에는 contentLayer만 남겨둔다면,
         //더 깔끔하게 정리할 수 있다.
         //이렇게 하면 MyItem의 내용은 변경되지만, HStack의 내용은 변경되지 않는다.
         
         var contentLayer: some View {
            HStack {
                 MyItem(title: "Apples", count: 1, color: .red)
                 MyItem(title: "Oranges", count: 10, color: .orange)
                 MyItem(title: "Bananas", count: 34, color: .yellow)
         }
    }
         */

    }
}


#Preview {
    ExtractSubviewsBootcamp()
}

//subview를 extract 하는 법 2
//이렇게 자동으로 struct을 생성해준다
//this view is same thing as creating a new file.
//which means we can add variables into this view.
struct MyItem: View {
    
    //변수설정
    let title: String
    let count: Int
    let color: Color
    
    var body: some View {
        VStack {
            Text("\(count)")
            Text(title)
        }
        .padding()
        .background(color)
        .clipShape(.buttonBorder)
    }
}


//--------------------------------------------------------
//subview로 빼는것을 하기 전에, 지난 강의에서 배운 것처럼 해본다.
//extract a part of the view
var myItems: some View {
    VStack {
        //data in this item are gonna be static. not dynamic.
        //-> 이 안에 있는 데이터는 안바뀐다.
        //e.g. Text("1")을 Text("2")로 바꿀 수 없다.
        //그렇기 때문에 만약 이 안의 데이터를 변경하고 싶다면,
        //그런 상황에서는 차라리 subview로 extract하는 것이 좋다
        Text("1")
        Text("Apples")
    }
    .padding()
    .background(Color.red)
    .clipShape(.buttonBorder)
}
 

0개의 댓글