Search code examples
swiftswiftuicombineswiftui-list

Force deselection of row in SwiftUI List view


I am using a List with a selection Binding. My expectation is that clearing the selection should update the List to not have any selected rows but the row UI remains selected.

Here is the example code:

struct ContentView: View {
    @State private var selection: String?

    let names = [
        "a",
        "b",
        "c",
        "d"
    ]

    var body: some View {
        NavigationView {
            VStack {
                List(names, id: \.self, selection: $selection) { name in
                    Text(name)
                }

                Button("Deselect") {
                    self.selection = nil
                }
            }
        }
    }
}

I expect that when clearing the selection on button press, the list should update to not have any selection but it remains selected.

Deselection image


Solution

  • Working on iOS 16

    import SwiftUI
    
            struct listSelection: View {
                
                @State private var selection: String?
                
                let names = [
                    "a",
                    "b",
                    "c",
                    "d"
                ]
                
                var body: some View {
                    NavigationView {
                        VStack {
                            List(names, id: \.self, selection: $selection) { name in
                                Text(name)
                            }
                            .id(UUID())
                            
                            Button("Deselect") {
                                selection = nil
                            }
                        }
                    }
                }
            }
    

    enter image description here