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.