LoginSignup
23
20

More than 3 years have passed since last update.

SwiftUIでCollectionViewのようなレイアウトを整えてみる

Last updated at Posted at 2019-08-08

この記事について

SwiftUIでUIKitでいうところのCollectionViewのような見た目のレイアウトを
QGridというライブラリを使用するとさくっと作れるよって話です。

最後の方はおまけのようなものなのですが、PR投げてみたって話です。

SwiftUIでCollectionViewのデザインを作るにはList?

Listで良しなにって感じなんですかね?

スクリーンショット 2019-08-06 19.01.34.png
SwiftUI-Cheat-Sheet

QGridというOSS

QGridDemo.gif

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

スクリーンショット 2019-08-06 19.14.39.png

気になった箇所に対して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からは見えてない状態になります。

スクリーンショット 2019-08-08 12.16.28.png

(data.count % col > 0)であればdata.count % colだけ最終行にCellを追加するようなPRを送らせてもらいました。

結果

Mergeされました:raised_hands:

スクリーンショット 2019-08-08 12.22.51.png

PR内のコメントでいくつかアドバイスを頂きつつ修正を重ねたのですが、
確かにこっちほうが良い!という納得感もありながら改善していけたのはすごく貴重な経験でした:pray:

23
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
20