繁体   English   中英

listRowBackground 移除选择样式

[英]listRowBackground removes selection style

在 SwiftUI List上使用listRowBackground时,所选项目不再突出显示。 NavigationLink使用ButtonStyle也不起作用。

对此有任何理智的解决方法吗?

示例代码:

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())
        }
    }
}

尽管 Apple 的文档中没有记录,但设置.listRowBackground将明智地删除选择行为。 如果您设置与默认选择颜色相匹配的Color.grey背景,会发生什么情况? 苹果现在应该选择不同的颜色吗? 他们如何确定对比度足够高,让用户判断选择是否处于活动状态?

幸运的是,您可以使用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)
            }
        }
    }
}

这是在行动:

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

暂无
暂无

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

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