Supersheep
Supersheep

Reputation: 256

SwiftUI List on macOS: highlighting content in the selected row?

In a SwiftUI List, when a row is selected, a blue selection is drawn in the selection, and foreground Text with the default primary color is automatically made white. For other views with custom colors, I'd like to be able to make sure they become tinted white to match the system apps. For example, see the blue dot on the selected row:

list

Example code:

List(selection: $selection) {
    ForEach(0..<4) { index in
        HStack {
            Image(systemName: "circle.fill")
                .foregroundColor(.blue)
            Text("Test")
        }
        .tag(index)
    }
}

Any tips on how to achieve the correct result here? 🙏

With NSTableCellView, there is the backgroundStyle property, but I couldn't find anything like this.

I'm also looking to customize not just a single SF Symbol image, but also a RoundedRectangle that is drawn with a custom foreground color that I want to become white upon selection.

Upvotes: 5

Views: 1247

Answers (1)

user1046037
user1046037

Reputation: 17725

Approach

  • Use a Label for the cell

Code

struct ContentView: View {
    
    @State private var selection: Int?
    
    var body: some View {
        List(selection: $selection) {
            ForEach(0..<4) { index in
                Label("Test", systemImage: "circle.fill")
                .tag(index)
            }
        }
    }
}

Screenshot

Highlighted Cell Image Color

Upvotes: 4

Related Questions