LazyVGrid, LazyHGrid and GridItems

Updated:

🔷 LazyGrid

  • A container view that arranges its child views in a grid that grows that vertically or horizontally creating items only as needed.

photo

🔶 LazyVGrid

  • 아래의 예시는 instagram 스타일의 만든 LazyVStack 예시 입니다
struct LazyGrid: View {

  // columns 의 갯수를 3개로 설ㅓ
	let columns: [GridItem] = [
		GridItem(.flexible(), spacing: 6, alignment: nil),
		GridItem(.flexible(), spacing: 6, alignment: nil),
		GridItem(.flexible(), spacing: 6, alignment: nil)
	]

var body: some View {

ScrollView {

// Hero 부분 (위에 사진 부분)
Rectangle()
.fill(Color.orange)
.frame(height: 400)


LazyVGrid(
columns: columns,
alignment: .center,
spacing: 6,
pinnedViews: [.sectionHeaders] ) {
  // section 으로 나눔
Section(header:
      Text("Section 1")
      .foregroundColor(.white)
      .font(.title)
      .frame(maxWidth: .infinity, alignment: .leading)
      .background(Color.blue)
      .padding()

// 총 20개의 frame 반복
) {
ForEach(0..<20) { index in
Rectangle()
  .frame(height: 150)
}
} //: Section 1

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)
}
} //: Section 2
}
}
}

}

스크린샷

🔶 LazyHGrid

  • 넷플릭스 처럼 가로로 스크롤 하면서 Grid 뷰를 보여주는 형태의 예시 입니다
struct LazyGrid: View {

	// title 1000 개 만듬
	let title = Array(1...1000).map {"목록 \($0)"}

	// 화면을 그리드형식으로 채워줌
	let layout : [GridItem] = [
		GridItem(.flexible(maximum: 80)),
		GridItem(.flexible(maximum: 80)),
	]

var body: some View {

// scrollView horizontal 로 수정
ScrollView (.horizontal) {
// LazyHGrid
LazyHGrid(rows: layout, spacing: 20) {
ForEach(title, id: \.self) { i in
  VStack {
    Capsule()
      .fill(Color.yellow)
      .frame(height: 30)
    Text(i)
      .foregroundColor(.secondary)
  }
}
}
.padding(.horizontal)
} //: SCROLL
}

}

스크린샷


🗃 Reference

Apple Developer official docs : LazyVGrid, LazyHGrid - https://developer.apple.com/documentation/swiftui/lazyvgrid

LazyVGrid, LazyHGrid, and GridItems in SwiftUI - https://www.youtube.com/watch?v=vHvb7LH8VuE&list=PLwvDm4VfkdphqETTBf-DdjCoAvhai1QpO&index=17

Categories:

Updated:

Leave a comment