SwiftUI Lists & Forms Edit Mode

Edit Mode

Enable reordering and deletion in lists by toggling EditMode.


Example: Built-in EditButton

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct EditButtonDemo: View {
  @State private var items = ["A","B","C"]
  var body: some View {
NavigationStack {
  List {
    ForEach(items, id: \.self) { Text($0) }
      .onDelete { items.remove(atOffsets: $0) }
      .onMove { items.move(fromOffsets: $0, toOffset: $1) }
  }
  .navigationTitle("Edit Mode")
  .toolbar { EditButton() }
}
} }


Example: Custom toggle

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct EditCustomDemo: View {
  @State private var items = ["A","B","C"]
  @State private var editMode: EditMode = .inactive
  var body: some View {
VStack {
  List {
    ForEach(items, id: \.self) { Text($0) }
      .onDelete { items.remove(atOffsets: $0) }
      .onMove { items.move(fromOffsets: $0, toOffset: $1) }
  }
  .environment(\.editMode, $editMode)
  Button(editMode.isEditing ? "Done" : "Edit") { editMode.toggle() }
}
} } private extension EditMode { mutating func toggle() { self = (isEditing ? .inactive : .active) } }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *