edit a list in swiftui in swift

Here are the steps to enable editing for a List in SwiftUI, and allow the user to delete or move the rows:

  1. Add the EditButton in the navigation bar of the view. This button allows the user to toggle the editing mode of the List:
main.swift
struct ContentView: View {
    @State private var items = ["Item 1", "Item 2", "Item 3"]

    var body: some View {
        NavigationView {
            List {
                ForEach(items, id: \.self) { item in
                    Text(item)
                }
                .onDelete(perform: deleteItem)
                .onMove(perform: moveItem)
            }
            .navigationBarTitle("Items")
            .navigationBarItems(trailing: EditButton())
        }
    }

    func deleteItem(at offsets: IndexSet) {
        items.remove(atOffsets: offsets)
    }

    func moveItem(from source: IndexSet, to destination: Int) {
        items.move(fromOffsets: source, toOffset: destination)
    }
}
707 chars
26 lines
  1. Add the onDelete() and onMove() modifiers to the ForEach inside the List. These modifiers will be called when the user tries to delete or move a row. In our example, we use them to call the deleteItem() and moveItem() functions that update the items array.

  2. Implement the deleteItem() and moveItem() functions to update the items array according to the action taken by the user. In our example, we use the remove(atOffsets:) and move(fromOffsets:toOffset:) methods to manipulate the items array.

With these steps in place, the user will be able to delete or move rows in the List by tapping the EditButton.

gistlibby LogSnag