LoginSignup
1
1

[SwiftUI] Listのスペースをmodifierで追加する

Posted at

はじめに

SwiftUIのListに対してpadding以外の方法でスペース追加ができるのか調べてみました
iOS17以降ではlistSectionSpacingを使うことでListのセクションにスペースが追加できるようになっていました

環境

Xcode 15.2

内容

例えばこのようなシンプルなListの実装があるとして

struct ListSpacingView: View {
    var body: some View {
        List {
            Section {
                Text("HogeHoge")
                Text("HogeHoge")
                Text("HogeHoge")
            }

            Section("Section Title") {
                Text("HogeHoge")
                Text("HogeHoge")
                Text("HogeHoge")
            }
        }
        .listStyle(.insetGrouped)
    }
}

このListのセクションやセルに対してのスペースをmodifierを使って実装します

listRowSpacing

iOS15以降で使えるlistRowSpacingを使うことでセルのスペースは簡単に追加することができます

struct ListSpacingView: View {
    var body: some View {
        List {
            Section {
                Text("HogeHoge")
                Text("HogeHoge")
                Text("HogeHoge")
            }

            Section("Section Title") {
                Text("HogeHoge")
                Text("HogeHoge")
                Text("HogeHoge")
            }
        }
        .listStyle(.insetGrouped)
+       .listRowSpacing(10.0)
    }
}

リストのstyleが違うと見え方も変わります。わかりやすくスペースを20追加したものを表示しました

  • .plain

  • .grouped

listSectionSpacing

iOS17以降ではlistSectionSpacingでセクションのスペースを追加することができます

struct ListSpacingView: View {
    var body: some View {
        List {
            Section {
                Text("HogeHoge")
                Text("HogeHoge")
                Text("HogeHoge")
            }

            Section("Section Title") {
                Text("HogeHoge")
                Text("HogeHoge")
                Text("HogeHoge")
            }
        }
        .listStyle(.insetGrouped)
+       .listSectionSpacing(30)
    }
}

スペース:030100

  • .plain

  • .grouped

ListSectionSpacing

スペースの値ではなく
static let compact: ListSectionSpacingを渡すこともできます

static func custom(CGFloat) -> ListSectionSpacingこちらで値を指定することもできるみたいです。直接スペースの値を入れるのと変わらない?🧐

  • .listSectionSpacing(.compact)

  • .listSectionSpacing(.custom(30))

    .listSectionSpacing(30)と同じ効果のようですね

おわりに

各セクションでスペースの値を変えたいなどあれば、paddingを使う方が良いとは思いつつ、Listに対してのmodifierで要件が満たせる場合は積極的に使いたいと思いました

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