[SwiftUI]リスト(List)のセクションの背景色を変えるには?

SwiftUI

どうも、ちょげ(@chogetarou)です。

リストのセクションの背景色を設定する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Listのセクションの背景色を変えるには、listRowInsets修飾子とbackground修飾子を使います。

まず、Sectionの引数「header」のビューに「listRowInsets(EdgeInsets())」を付与します。

次に、ListのSectionの引数「header」のビューにbackground修飾子を付与します。

そして、background修飾子の引数に背景色を指定します。

List {
    Section(
        header: HeaderView()
                    .background(/*背景色*/)
                    .listRowInsets(EdgeInsets())
    ) {
        //リストの要素
    }
}

listRowInsets修飾子とbackground修飾子を使えば、セクションの背景色を変えることができます。

使用例

以下は、使用例です。

struct ContentView: View {
    
    var body: some View {
        VStack {
            List {
                Section(
                    header: HStack {
                        Text("Section")
                            .foregroundColor(.white)
                            .padding()
                        Spacer()
                    }
                    .background(Color.blue)
                    .listRowInsets(EdgeInsets())
                    
                ) {
                    ForEach (1..<6, id: \.self) { index in
                        Text("\(index)")
                    }
                }
            }
            .listStyle(GroupedListStyle())
        }
    }
}

コメント

タイトルとURLをコピーしました