简体   繁体   中英

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?

对比度差

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM