Lazy가 붙으면 화면에 표시되는 부분에 한해 메모리를 로드하고 재사용한다.
즉 데이터가 많은 경우 이를 한 번에 로드하여 보여주려면 로드하는데 시간이 걸리고 성능이 저하될 수 있으나
LazyGrid 나 LazyStack같은 것을 사용하면 실제 화면에 보여주는 부분만 메모리를 로드하고 재사용하기 때문에 효율이 좋다.
이 글을 쓰는 이유는 LazyVGrid 안에서 Section을 사용하여 화면 스크롤 시 Section의 Header가 고정되어 상단에 계속 노출시키는 방법을 알게 되었기 때문이다.
struct GridBootcamp: View {
let columns: [GridItem] = [
GridItem(.flexible(), spacing: nil, alignment: nil),
GridItem(.flexible(), spacing: nil, alignment: nil),
GridItem(.flexible(), spacing: nil, alignment: nil)
]
var body: some View {
ScrollView {
Rectangle()
.fill(.orange)
.frame(height: 300)
LazyVGrid(
columns: columns,
alignment: .center,
spacing: nil,
pinnedViews: [.sectionHeaders]
) {
Section(
header:
Text("Section 1")
.font(.title)
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
) {
ForEach(0..<20) { index in
Rectangle()
.fill(.blue)
.frame(height: 150)
}
}
Section(
header:
Text("Section 2")
.font(.title)
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
) {
ForEach(0..<20) { index in
Rectangle()
.fill(.green)
.frame(height: 150)
}
}
}
}
}
}
스크롤 시 고정시킬 대상을 LazyVGrid 생성자의 pinnedViews에 명시하는데
pinnedViews 타입은 PinnedScrollableViews로 sectionHeaders, sectionFooters가 있다.
위의 예제에서는 header만 추가하여 고정시켰다.
더보기
LazyVGrid Bootcamp
'iOS > SwiftUI' 카테고리의 다른 글
@StateObject vs @ObservedObject (1) | 2024.05.13 |
---|---|
Lifecycle event modifier (3) | 2023.11.23 |
NavigationStack (0) | 2023.11.21 |
ProgressView (0) | 2023.11.21 |
TextField & SecureField (0) | 2023.11.21 |