1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftUIでグリッドレイアウトを実装する方法

Posted at

はじめに

現在作成中のアプリで、グリッドレイアウトを実装する必要があったため、実装方法をメモします。

グリッドレイアウトとは?

グリッドレイアウトとは、ホームページのデザイン手法の一つで、画面やページを格子状に分割し、これを組み合わせてブロックを並べた時のようなデザインにする手法のことです。

SwiftUIでグリッドレイアウトを実装する方法

グリッドレイアウトを実装するには、LazyVGrid,LazyHGridを使用します。ただしLazyGridは、ios14から提供されたものです。

LazyVGrid:縦方向に要素を並べる。

LazyHGrid:横方向に要素を並べる。

書き方

let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        ...
    ]
LazyVGrid(columns: columns){
    要素1
    要素2
    要素3
    ...
}
let rows = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        ...
    ]
LazyHGrid(rows: rows) {
    要素1
    要素2
    要素3
    ...
}

引数について

引数には、配列を指定する必要があり、要素はGridItem型で指定する必要があります。
また、GridItemの引数は、以下が指定可能です。

init(GridItem.Size, spacing: CGFloat?, alignment: Alignment?)

パラメータ 説明
size 固定のサイズ(.fixed)
最小と最大で設定した値の範囲内で画面に収まるサイズ(.flexible)
画面サイズに合わせたサイズ(.adaptive)
spacing GridItem間のサイズ
alignment GridItemの配置

使用イメージ

struct ContentView: View {
    let columns = [
            GridItem(.fixed(30), spacing: 1),
            GridItem(.fixed(60), spacing: 10),
            GridItem(.fixed(90), spacing: 20),
            GridItem(.fixed(10), spacing: 50)
        ]
    var body: some View {
        ScrollView(.horizontal) {
            LazyVGrid(columns: columns, spacing: 5) {
                ForEach(0...300, id: \.self) { _ in
                    Color.red.frame(width: 30)
                    Color.green.frame(width: 30)
                    Color.blue.frame(width: 30)
                    Color.yellow.frame(width: 30)
                }
            }
        }
    }
}

スクリーンショット 2023-04-18 0.46.43.png

struct ContentView: View {
    let rows = [
            GridItem(.fixed(30), spacing: 1),
            GridItem(.fixed(60), spacing: 10),
            GridItem(.fixed(90), spacing: 20),
            GridItem(.fixed(10), spacing: 50)
        ]
    var body: some View {
        ScrollView(.horizontal) {
            LazyHGrid(rows: rows, spacing: 5) {
                ForEach(0...300, id: \.self) { _ in
                    Color.red.frame(width: 30)
                    Color.green.frame(width: 30)
                    Color.blue.frame(width: 30)
                    Color.yellow.frame(width: 30)
                }
            }
        }
    }
}

スクリーンショット 2023-04-18 0.43.51.png

おわりに

LazyGridを使用すると簡単にグリッドレイアウトが実装できるので、今後も頻繁に使用する気がします。また、もっと簡単に実装できる方法があれば、ご教授いただけますと幸いです。

参考記事

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?