1
1

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 5 years have passed since last update.

SwiftUI 4泊5日の旅(3日目:実装例① GridLayout)

Last updated at Posted at 2020-05-04

はじめに

前回まではSwiftUIの基礎でしたが、今日から3日間は汎用的に使えそうなレイアウトを作っていきます。

グリッドレイアウト

今日はタイル状の見た目です。フォトギャラリーなんかでよくあるやつです。

ContentView.swift
import SwiftUI

// 表示モデル
struct Cell: Identifiable {
    let id = UUID()
    let imageName: String
}

// 配列を数個ずつ区切る拡張関数
extension Array {
    func chunk(into columnCount:Int) -> [[Element]] {
        var chunkedArray = [[Element]]()
        for index in 0...self.count {
            if index % columnCount == 0 && index != 0 {
                chunkedArray.append(Array(self[index - columnCount..<index]))
            } else if(index == self.count) {
                chunkedArray.append(Array(self[index - (index % columnCount)..<index]))
            }
        }
        return chunkedArray
    }
}

// 本体
struct ContentView: View {
    var body: some View {
        let cells = [Cell](repeating: Cell(imageName: "tonionagauzzi"), count: 20)
        let chunkedCells = cells.chunk(into: 4)
        return List {
            ForEach(0..<chunkedCells.count) { index in
                HStack {
                    ForEach(chunkedCells[index]) { cell in
                        Image(cell.imageName)
                            .resizable()
                            .scaledToFit()
                    }
                }
            }
        }
        .edgesIgnoringSafeArea([.leading, .trailing])
        .padding(EdgeInsets.init(top: 0, leading: -20, bottom: 0, trailing: -20))
    }
}

// プレビュー
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

配列の要素数を変えても↓いい感じの見た目に調整してくれます。

これでコード量は50行に満たないので、UIKitでゴリゴリ作るより間違いなく早いですね。
Xib、Storyboardよりバージョン管理しやすいのも特長です。
とはいえネストが深いと1階層変えるだけでとんでもないDiffになるので、バージョン管理の悩みは尽きませんが…

ちなみにQGridとかを使うと、もっと綺麗なレイアウトを簡単に作れます。

最後に

次回はもっと複雑なレイアウトを、同じくらい短いコードで実現するのが目標です。
やっと追いついた。今日も心の中では旅を満喫しています。

お昼は山形の冷たい肉そばをいただきました😋

夜は仙台名物牛タン。乾杯!Prost!!(🏎)
※写真は2017年GW旅行のものです

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?