23.12.15 TIL SwiftUI 15. LazyVGrid, LazyHGrid, and GridItems

Hay·2023년 12월 15일
0

SwiftUI_Beginner

목록 보기
11/19

LazyVGrid, LazyHGrid, and GridItems

  • swiftUI 의 all grid is lazy by default
  • 그리드를 이용해서 섹션 만들기 + 스크롤링도 할 수 있다
  • GridItem의 .flexible을 많이 사용한다.
  • LazyVGrid의 pinnedViews를 이용해서 스크롤링할때 header가 같이 움직이게 할 수도 있다
import SwiftUI

//Grid는 주로 ScrollView, ForEach와 함께 사용된다.
//Grid has rows and columns.
//Grids are automatically lazy.

struct GridBootcamp: View {
    
    let columns: [GridItem] = [
        //real world example
        GridItem(.flexible(), spacing: 6, alignment: nil),
        GridItem(.flexible(), spacing: 6, alignment: nil),
        GridItem(.flexible(), spacing: 6, alignment: nil)
    ]
    
    var body: some View {
        ScrollView{
            
            Rectangle()
                .fill(Color.orange)
                .frame(height: 400)
            
            LazyVGrid(
                columns: columns,
                alignment: .center,
                spacing: 6,
                pinnedViews: [.sectionHeaders], //여기에 header를 pin할 수도 있다.
                content: {
                    Section(header: 
                                Text("Section 1")
                                .foregroundColor(.white)
                                .font(.title)
                                .frame(maxWidth: .infinity, alignment: .leading)
                                .background(Color.blue)
                                .padding()
                    ) {
                        ForEach(0..<20) { index in
                            Rectangle()
                                .frame(height: 150)
                        }
                    }
                    
                    Section(header:
                                Text("Section 2")
                                .foregroundColor(.white)
                                .font(.title)
                                .frame(maxWidth: .infinity, alignment: .leading)
                                .background(Color.red)
                                .padding()
                    ) {
                        ForEach(0..<20) { index in
                            Rectangle()
                                .fill(Color.green)
                                .frame(height: 150)
                        }
                    }

                })
        }
        
    }
    
}

#Preview {
    GridBootcamp()
}


0개의 댓글