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

【SwiftUI】Listで選択行の背景色を変える

Posted at

まずはコードを見てください。

import SwiftUI

struct Collection: Identifiable {
    let id = UUID()
    let name: String
}

struct ContentView: View {
    @State var collections = [
        Collection(name: "木﨑太郎"),
        Collection(name: "空道太郎"),
        Collection(name: "松本直也"),
        Collection(name: "子安裕樹"),
    ]
    @State var selectionIndex: Int? =  2
    
    var body: some View {
        List() {
            ForEach(0..<collections.count, id: \.self) { index in
                HStack {
                    Text(collections[index].name)
                    Spacer()
                }
                .listRowBackground(selectionIndex == index ? Color(UIColor.systemGray4) : nil)
                .contentShape(Rectangle())
                .onTapGesture {
                    selectionIndex = index
                }
            }
        }
    }
}

結果はこうなります。
01.png
この行で背景色を指定しています。

.listRowBackground(selectionIndex == index ? Color(UIColor.systemGray4) : nil)

色はUIColor.systemGrayで指定するとダークモードでもいい感じにしてくれます。
02.png
好きな色を指定したい場合はAsset Catalogを作るといいでしょう。

0
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
0
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?