【SwiftUI】LazyVGrid - ヘッダー編-
今回は、LazyVGridの表示で、ヘッダーの固定有無の場合において表示について記載します。
1. 固定した場合と固定しない場合を比較
挙動は以下の通りになります。動画の画面上部は、ヘッダーを固定しておりません。動画の画面下部は固定しての表示になります。
・動画
・コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
private var colors: [Color] = [.blue, .yellow, .green] | |
var gridItems = Array(repeating: GridItem(.fixed(80.0)), count: 4) | |
var body: some View { | |
VStack { | |
ScrollView() { | |
LazyVGrid(columns: gridItems, spacing: 10) { | |
Section( | |
header: | |
Text("Section 1").font(.title).frame(maxWidth: .infinity, maxHeight: .infinity) | |
.background(RoundedRectangle(cornerRadius: 0) | |
.fill(Color.pink))) { | |
ForEach((0...30), id: \.self) { index in | |
CellContent(index: index, | |
color: colors[index % colors.count]) | |
} | |
} | |
} | |
} | |
ScrollView() { | |
LazyVGrid(columns: gridItems, spacing: 10,pinnedViews:.sectionHeaders) { | |
Section( | |
header: | |
Text("Section 1").font(.title).frame(maxWidth: .infinity, maxHeight: 100.0) | |
.background(RoundedRectangle(cornerRadius: 0) | |
.fill(Color.pink))) { | |
ForEach((0...30), id: \.self) { index in | |
CellContent(index: index, | |
color: colors[index % colors.count]) | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
2.固定した場合の挙動の注意について
上にスクロールすると下のリストが突き抜けますので、上からViewを被せるか何か対応が必要そうです。
・動画
・コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ScrollView() { | |
LazyVGrid(columns: gridItems, spacing: 10,pinnedViews:.sectionHeaders) { | |
Section( | |
header: | |
Text("Section 1").font(.title).frame(maxWidth: .infinity, maxHeight: 100.0) | |
.background(RoundedRectangle(cornerRadius: 0) | |
.fill(Color.pink))) { | |
ForEach((0...30), id: \.self) { index in | |
CellContent(index: index, | |
color: colors[index % colors.count]) | |
} | |
} | |
}.edgesIgnoringSafeArea(.all) | |
}.background(Color.gray) |