简体   繁体   English

如何更改 SwiftUI 中选定列表项的文本颜色?

[英]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?如何更改 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并在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.注意:您可以使用浅色/深色模式变体设置在颜色资产中创建的自定义颜色,而不是.blue ,因此在这些模式下选择的颜色不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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