Reputation: 1225
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?
var itemList: some View {
List{
ForEach(items, id: \.self, selection: $selectedItem) { item in
NavigationLink(
destination: ItemDetail(item: item)
) {
ItemRow(item: item)
}
}
}
}
Upvotes: 1
Views: 3286
Reputation: 258355
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.
Upvotes: 2