この記事について
SwiftUIでUIKitでいうところのCollectionViewのような見た目のレイアウトを
QGridというライブラリを使用するとさくっと作れるよって話です。
最後の方はおまけのようなものなのですが、PR投げてみたって話です。
SwiftUIでCollectionViewのデザインを作るにはList?
Listで良しなにって感じなんですかね?
[SwiftUI-Cheat-Sheet](https://github.com/SimpleBoilerplates/SwiftUI-Cheat-Sheet)QGridというOSS
QGrid is the missing SwiftUI collection view. It uses the same approach as SwiftUI's List view, by computing its cells on demand from an underlying collection of identified data.
どうやら、SwiftUIのListのようにうまくやってるっぽい
QGrid
動かしてみる
import SwiftUI
import QGrid
struct CollectionView: View {
var body: some View {
QGrid(landmarkData,
columns: 2,
columnsInLandscape: 4,
vSpacing: 50,
hSpacing: 20,
vPadding: 100,
hPadding: 20) { landmark in
Cell(content: landmark)
}
}
}
struct Cell: View {
var content: Landmark
var body: some View {
HStack {
VStack(alignment: .center) {
self.content.image
.resizable()
.frame(width: 150, height: 150)
.clipShape(Circle())
.overlay(Circle().stroke(Color.orange, lineWidth: 2.0))
Text(self.content.name)
}
}
}
}
#if DEBUG
struct CollectionView_Previews: PreviewProvider {
static var previews: some View {
CollectionView()
}
}
#endif
気になった箇所に対してPR投げてみた
// Dirty little hack to handle layouting of the last row gracefully :
.opacity(!isLastRow || column.id < self.data.count % self.cols ? 1.0 : 0.0)
どうやら、最終行にCellを表示させる際
(data.count % col > 0)余りがある場合、必要に応じて表示/非表示にしている感じでした。
以下の図の場合
15個のCellが画面上には描画されており3つ非表示にしているためUserからは見えてない状態になります。
(data.count % col > 0)
であればdata.count % col
だけ最終行にCellを追加するようなPRを送らせてもらいました。
結果
Mergeされました
PR内のコメントでいくつかアドバイスを頂きつつ修正を重ねたのですが、
確かにこっちほうが良い!という納得感もありながら改善していけたのはすごく貴重な経験でした