Search code examples
swiftuiswiftui-list

How can I change the text color of selected list items in SwiftUI?


How can I change the text color of selected list items in SwiftUI? And can I do this dynamically so that if is always a contrasting color to the selected row's background color?

Poor contrast

var itemList: some View {
    List{
        ForEach(items, id: \.self, selection: $selectedItem) { item in
             NavigationLink(
                 destination: ItemDetail(item: item)
             ) {
                 ItemRow(item: item)
             }
        }
    }
}

Solution

  • There might be variants but in general you have to pass somehow selection into view with row text and apply foreground color conditionally, like

         NavigationLink(
             destination: ItemDetail(item: item)
         ) {
             ItemRow(item: item, selected: item == selectedItem)
         }
    

    and in ItemRow

        Text(item.title)
            .foregroundColor(selected ? .blue : .labelColor)
    

    Note: instead of .blue you can set your custom color created in color assets with light/dark mode variants, so selection be differently colored in those modes.