Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Change List row Highlight colour when tapped

The default colour of a list row when tapped is grey.

I know how to change background colour using .listRowBackground, but then it changes to the whole list.

How can I change to a custom colour when tapped, so ONLY the tapped row stays red?

import SwiftUI

struct ExampleView: View {
    @State private var fruits = ["Apple", "Banana", "Grapes", "Peach"]

    var body: some View {
        NavigationView {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit)
                }
                .listRowBackground(Color.red)

            }


        }
    }


}

struct ExampleView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleView()
    }
}

enter image description here

like image 741
Mane Manero Avatar asked Dec 02 '19 15:12

Mane Manero


2 Answers

First, you want the .ListRowBackground modifier on the row not the whole list and then use it to conditionally set the row background color on each row. If you save the tapped row's ID in a @State var, you can set the row to red or the default color based on selection state. Here's the code:

import SwiftUI

struct ContentView: View {
    @State private var fruits = ["Apple", "Banana", "Grapes", "Peach"]
    @State private var selectedFruit: String?

    var body: some View {
        NavigationView {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit)
                        .onTapGesture {
                            self.selectedFruit = fruit
                    }
                    .listRowBackground(self.selectedFruit == fruit ? Color.red : Color(UIColor.systemGroupedBackground))
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
like image 139
Chuck H Avatar answered Sep 19 '22 17:09

Chuck H


Following on @Chuck H,

I'm using:

        List {
            ForEach(viewModel.sharingGroups, id: \.self) { group in
                Button(action: {
                    self.selectedGroup = group
                }, label: {
                    Text(group.name)
                })
                .listRowBackground(self.selectedGroup == group ? Color.gray : Color(UIColor.systemGroupedBackground))
            }
        }

If you use a Button instead if Text directly, this enables me to tap anywhere on the row, not just on the text.

like image 22
Chris Prince Avatar answered Sep 18 '22 17:09

Chris Prince