MacOS SwiftUI: Is it impossible to clear a Table selection?

I figured it would be as simple as changing the selection variable back to nil, but that seemingly has no effect. The Table row stays selected, and if I press on it again, it won't trigger my .navigationDestination(). How can I resolve this? I found another post asking the same thing, with no resolution. The only way I can clear it is by clicking with my mouse somewhere else.

@State private var selectedID: UUID? = nil

Table(tableData, selection: $selectedID, sortOrder: $sortOrder)...

.navigationDestination(item: $selectedID, destination: { id in
                if let cycle = cycles.first(where: {$0.id == id}) {
                    CycleDetailView(cycle: cycle)
                        .onDisappear(perform: {
                            selectedID = nil
                        })
                }
            })
                
Answered by Claude31 in 812497022

Usually (at least that's how I use it), selection is a Set:

    @State private var selectedID: Set<UUID> = []

Of course, you have to extract from set to pass to navigation, but that's easy, as set has usually a single item. You could create a computed var to do so. .

Then, clearing the selection is simply done by resetting to empty set.

Accepted Answer

Usually (at least that's how I use it), selection is a Set:

    @State private var selectedID: Set<UUID> = []

Of course, you have to extract from set to pass to navigation, but that's easy, as set has usually a single item. You could create a computed var to do so. .

Then, clearing the selection is simply done by resetting to empty set.

The answer from @Claude31 solved it, but here is the additional code I added.

First I created a new variable to track what's being selected.

@State private var selectedCycle: Cycle? = nil

Then I watched for a change on the selectedID.

.onChange(of: selectedID, {
            if let id = selectedID.first {
                selectedCycle = cycles.first(where: {$0.id == id})
            }
        })

Then I added the onDisappear in my navigationDestination to clear what's selected.

.navigationDestination(item: $selectedCycle, destination: { cycle in
            CycleDetailViewMac(cycle: cycle)
                .onDisappear(perform: {
                    selectedID.removeAll()
                })
        })
MacOS SwiftUI: Is it impossible to clear a Table selection?
 
 
Q