swiftuiswiftui-list

List with different colour selection bar


I am new to SwiftUI, and I have a simple question. I want to create a list that when the user selects a value the highlighted bar is a different colour from the default system "blue".

Here is my list with the blue bar

This view is built with this code:

struct Test: View {
    @State private var selection: String?

       let names = [
           "Cyril",
           "Lana",
           "Mallory",
           "Sterling"
       ]

       var body: some View {
           NavigationStack {
               List(names, id: \.self, selection: $selection) { name in
                   Text(name)
               }
               .navigationTitle("List Selection")
           }
       }
}

I can't seem to change the colour of that bar. How can I do that?


Solution

  • For iOS, see this answer.

    For macOS, this color is determined by the user's macOS settings. This one:

    enter image description here

    If this is set to "multicolor", the color will be your app's "AccentColor", as in your asset catalog.

    As far as I know, there is no way to change this with the built-in List with a selection: parameter. You would need to roll your own selection mechanism. Here is a very simple example.

    @State private var selection: String?
    
    let names = [
        "Cyril",
        "Lana",
        "Mallory",
        "Sterling"
    ]
    
    var body: some View {
        NavigationStack {
            List(names, id: \.self) { name in
                
                Text(name)
                    .onTapGesture {
                        selection = name
                    }
                    .listRowBackground(name == selection ? Color.red : nil)
            }
            .navigationTitle("List Selection")
        }
    }