editMode environment variable
Source: Dev.to
Overview
@Environment(\.editMode) provides a binding to the edit mode state rather than a plain value.
When used with List and EditButton(), SwiftUI supplies the binding internally, so you rarely see an explicit declaration.
Default Behavior
EditButton()toggles theeditModeenvironment variable.Listobserves this change, switches to edit mode, updates the button title from Edit to Done, and shows the UI for deleting rows.- Even though
editModeisn’t declared in your view, it remains the single source of truth.
Manual Control
If you need to control edit mode yourself, declare your own state variable and bind it to the environment.
State Declaration
@State private var editMode: EditMode = .inactive
EditMode has three cases: .inactive, .active, and .transient.
Injecting the Binding
Use the .environment(\.editMode, $editMode) modifier to feed your state into SwiftUI’s environment, both for the parent view and any child views.
Parent View Example
NavigationStack {
VStack(spacing: 16) {
if editMode == .active {
Text("I appear only in Edit Mode")
.padding()
.background(.yellow)
}
Text("Always visible")
EditButton() // toggles SwiftUI’s editMode env var
Button("tap me for second view") {
isShowing.toggle()
}
}
.environment(\.editMode, $editMode) // bind our state to the env var
.fullScreenCover(isPresented: $isShowing) {
SecondContentView()
.environment(\.editMode, $editMode) // pass the binding to the child
}
}
Child View Example
struct SecondContentView: View {
@Environment(\.editMode) var editMode // binding from the environment
var body: some View {
NavigationStack {
VStack(spacing: 16) {
if editMode?.wrappedValue.isEditing == true {
Text("I appear only in Edit Mode")
.padding()
.background(.yellow)
}
}
}
}
}
editMode?.wrappedValue.isEditingchecks the actual edit‑mode state provided by the environment.- The child view receives the same binding, so toggling edit mode in the parent updates the child automatically.
Key Points
@Environment(\.editMode)is a binding, not a static value.- SwiftUI supplies the binding automatically for
List/EditButton(). - For manual control, declare a
@Statevariable of typeEditModeand bind it with.environment(\.editMode, $editMode). - Remember to propagate the binding to any child views that need to react to edit‑mode changes.