简体   繁体   中英

listRowBackground removes selection style

When using listRowBackground on a SwiftUI List there is no longer any highlighting of the selected item. Using a ButtonStyle for the NavigationLink does not work either.

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. What should happen if you set a background of Color.grey which matches the default selection color? 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:

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:

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

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