How to prevent editMode from being instantly deactivated/reactivated when a confirmation dialog appears?

Using the editMode environment var in conjunction with a confirmationDialog causes editMode to be automatically and instantly deactivated/reactivated when the confirmationDialog appears or disappears.

This behavior is clearly visible when observing the editMode variable via the onChange modifier.

How to avoid this behavior? Is this a bug?

import SwiftUI

fileprivate struct Element: Hashable, Identifiable {
    let id = UUID()
}

struct ContentView: View {
    @State private var elements: [Element] = [.init(), .init(), .init()]
    
    var body: some View {
        NavigationStack {
            List(
                $elements,
                editActions: .delete,
                rowContent: { $element in Text(String(describing: element.id)) }
            )
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    EditButton()
                        .disabled(elements.isEmpty)
                }
                ToolbarItem(placement: .topBarLeading) {
                    RemoveAllButton(elements: $elements)
                }
            }
        }
    }
}

fileprivate struct RemoveAllButton: View {
    @Environment(\.editMode) private var editMode
    @Binding var elements: [Element]
    @State private var isConfirmationDialogPresented: Bool = false
    
    var body: some View {
        Button(
            "Remove All",
            role: .destructive,
            action: { isConfirmationDialogPresented = true }
        )
        .confirmationDialog(
            "Remove \(elements.count) element(s)",
            isPresented: $isConfirmationDialogPresented,
            actions: {
                Button(
                    "Remove \(elements.count) element(s)",
                    role: .destructive,
                    action: {
                        $elements.animation().wrappedValue.removeAll()
                        editMode?.wrappedValue = .inactive
                    }
                )
            }
        )
        .opacity(isEditing ? 1 : 0)
        .onChange(of: editMode?.wrappedValue.isEditing, { (oldValue, newValue) in
            print(oldValue, newValue)
        })
    }
    
    private var isEditing: Bool {
        editMode?.wrappedValue.isEditing ?? false
    }
}

Tested with Xcode 16 beta 4.

Hi @piaume ,

I saw that you have filed a bug report, thanks so much! You'll be able to track the status of that.

To me, it looks like unexpected behavior, although there may be a reason for it due to the confirmation dialogue taking over focus on the screen, which may inadvertently change the editMode binding. I tried to use an Alert to work around it but did see the same behavior.

How to prevent editMode from being instantly deactivated/reactivated when a confirmation dialog appears?
 
 
Q