小学理科717236 views
小学算数1194618 views
LaTeX957300 views
世界の国560595 views
高校倫理1433119 views
教育148875 views
高校物理158224 views
高校生物549842 views
いろは2986023 views
Computer365120 views
Help
Tools

English

セクション(Section)の使い方

List 内で Section を使うと、項目をグループ分けして見やすく表示できます。設定画面や連絡先アプリのような、カテゴリ別の一覧表示に最適です。

Section の基本

Section はヘッダーとフッターを持つグループを作成します。

struct SettingsView: View {
    var body: some View {
        List {
            Section("アカウント") {
                Text("プロフィール")
                Text("パスワード変更")
                Text("メールアドレス")
            }
            
            Section("通知") {
                Text("プッシュ通知")
                Text("メール通知")
            }
        }
    }
}

引数に文字列を渡すだけで、自動的にヘッダーが表示されます。

ヘッダーとフッターのカスタマイズ

より複雑なヘッダーやフッターを作成したい場合は、header:footer: パラメータを使います。

struct ContentView: View {
    var body: some View {
        List {
            Section {
                Text("項目1")
                Text("項目2")
            } header: {
                Label("重要", systemImage: "star.fill")
                    .foregroundColor(.yellow)
            } footer: {
                Text("これらの項目は特に重要です")
                    .font(.caption)
            }
        }
    }
}

header と footer にはカスタムビューを渡せるため、アイコン付きのヘッダーや説明文付きのフッターを自由に作成できます。

動的なセクション

ForEach を使って、データからセクションを動的に生成することも可能です。

struct Contact: Identifiable {
    let id = UUID()
    var name: String
    var initial: String
}

struct ContactListView: View {
    let contacts = [
        "A": [Contact(name: "Alice", initial: "A"), 
              Contact(name: "Alex", initial: "A")],
        "B": [Contact(name: "Bob", initial: "B")],
        "C": [Contact(name: "Charlie", initial: "C")]
    ]
    
    var body: some View {
        List {
            ForEach(contacts.keys.sorted(), id: \.self) { key in
                Section(key) {
                    ForEach(contacts[key]!) { contact in
                        Text(contact.name)
                    }
                }
            }
        }
    }
}

Section のスタイル

ListStyle によって Section の見た目が変わります。

struct ContentView: View {
    var body: some View {
        List {
            Section("セクション1") {
                Text("項目A")
                Text("項目B")
            }
            
            Section("セクション2") {
                Text("項目C")
                Text("項目D")
            }
        }
        .listStyle(.insetGrouped)  // iOS の設定アプリ風
    }
}
.automatic

プラットフォームに応じた標準スタイル

.insetGrouped

角丸のグループ化されたスタイル。iOS の設定アプリで使われている見た目。

.plain

区切り線のみのシンプルなスタイル。ヘッダーは上部に固定される。

.sidebar

macOS や iPadOS のサイドバー向けスタイル。

セクションの折りたたみ

iOS 17 以降では、セクションを折りたたみ可能にすることもできます。

struct ContentView: View {
    var body: some View {
        List {
            Section("折りたたみ可能", isExpanded: .constant(true)) {
                Text("項目1")
                Text("項目2")
                Text("項目3")
            }
        }
    }
}

isExpanded に Binding を渡すことで、プログラムから開閉状態を制御できます。

Section を活用することで、大量のデータも整理された形で表示でき、ユーザーにとって使いやすい UI を実現できます。