EditButton selection gets cleared when confirmationDialog appears in SwiftUI List

I'm experiencing an issue where my List selection (using EditButton) gets cleared when a confirmationDialog is presented, making it impossible to delete the selected items.

Environment:

  • Xcode 16.0.1
  • Swift 5
  • iOS 18 (targeting iOS 17+)

Issue Description: When I select items in a List using EditButton and tap a delete button that shows a confirmationDialog, the selection is cleared as soon as the dialog appears. This prevents me from accessing the selected items to delete them.

Code:

State variables:

@State var itemsSelection = Set<Item>()
@State private var showDeleteConfirmation = false

List with selection:

List(currentItems, id: \.self, selection: $itemsSelection) { item in
    NavigationLink(value: item) {
        ItemListView(item: item)
    }
}
.navigationDestination(for: Item.self) { item in
    ItemViewDetail(item: item)
}
.toolbar {
    ToolbarItem(placement: .primaryAction) {
        EditButton()
    }
}

Delete button with confirmation:

Button {
    if itemsSelection.count > 1 {
        showDeleteConfirmation = true
    } else {
        deleteItemsSelected()
    }
} label: {
    Image(systemName: "trash.fill")
        .font(.system(size: 12))
        .foregroundStyle(Color.red)
}
.padding(8)
.confirmationDialog(
    "Delete?",
    isPresented: $showDeleteConfirmation,
    titleVisibility: .visible
) {
    Button("Delete", role: .destructive) {
        deleteItemsSelected()
    }
    Button("Cancel", role: .cancel) {}
} message: {
    Text("Going to delete: \(itemsSelection.count) items?")
}

Expected Behavior: The selected items should remain selected when the confirmationDialog appears, allowing me to delete them after confirmation.

Actual Behavior: As soon as showDeleteConfirmation becomes true and the dialog appears, itemsSelection becomes empty (count = 0), making it impossible to delete the selected items.

What I've Tried:

  • Moving the confirmationDialog to different view levels
  • Checking if this is related to the NavigationLink interaction

Has anyone encountered this issue? Is there a workaround to preserve the selection when showing a confirmation dialog?

Answered by jonathanrtv in 865448022

Ok, never mind, I figured it out. I was placing the .toolBar with the EditButton in the wrong view position, which wasn't able to inject the environment value into the children's views and was causing some weird re-rendering.

Accepted Answer

Ok, never mind, I figured it out. I was placing the .toolBar with the EditButton in the wrong view position, which wasn't able to inject the environment value into the children's views and was causing some weird re-rendering.

EditButton selection gets cleared when confirmationDialog appears in SwiftUI List
 
 
Q