简体   繁体   English

listRowBackground 移除选择样式

[英]listRowBackground removes selection style

When using listRowBackground on a SwiftUI List there is no longer any highlighting of the selected item.在 SwiftUI List上使用listRowBackground时,所选项目不再突出显示。 Using a ButtonStyle for the NavigationLink does not work either.NavigationLink使用ButtonStyle也不起作用。

Are there any sane workaround for this?对此有任何理智的解决方法吗?

Example code:示例代码:

struct ContentView: View {
    struct ContentSection: Identifiable {
        let id = UUID()
        let title: String
        let items: [String]
    }

    var sections = [
        ContentSection(title: "Lorem", items: ["Dolor", "Sit", "Amed"]),
        ContentSection(title: "Ipsum", items: ["Consectetur", "Adipiscing", "Elit"])
    ]

    var body: some View {
        NavigationView {
            List {
                ForEach(sections) { section in
                    Section {
                        ForEach(section.items, id: \.self) { item in
                            NavigationLink(destination: Text(item)) {
                                Text(item)
                            }
                            .listRowBackground(Color.orange.ignoresSafeArea())
                        }
                    } header: {
                        Text(section.title)
                    }
                }
            }
            .listStyle(GroupedListStyle())
        }
    }
}

Although it is not documented in Apple's documentation, setting a .listRowBackground will wisely remove selection behaviour.尽管 Apple 的文档中没有记录,但设置.listRowBackground将明智地删除选择行为。 What should happen if you set a background of Color.grey which matches the default selection color?如果您设置与默认选择颜色相匹配的Color.grey背景,会发生什么情况? Should Apple pick a different color now?苹果现在应该选择不同的颜色吗? How can they be sure the contrast is high enough for the user to tell if the selection is active?他们如何确定对比度足够高,让用户判断选择是否处于活动状态?

Fortunately you can implement your own selection behaviour using List(selection:, content:) and then comparing the item being rendered in ForEach with the current selected item and changing the background yourself:幸运的是,您可以使用List(selection:, content:)实现自己的选择行为,然后将ForEach中呈现的项目与当前选定的项目进行比较并自行更改背景:

struct ContentView: View {
    @State var selection: Int?
    
    var body: some View {
        List(selection: $selection) {
            ForEach(1...5, id: \.self) { i in
                Text(i, format: .number)
                    .listRowBackground(i == selection ? Color.red.opacity(0.5) : .white)
                    .tag(i)
            }
        }
    }
}

Here it is in action:这是在行动:

显示选择随自定义颜色变化的动画

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

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