Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Implementing Swipe to Delete in SwiftUI
Written by Team Kodeco

It is a common requirement in mobile app development to give users the ability to remove items from a list, often accomplished with a swipe-to-delete gesture. In SwiftUI, this functionality is easy to add with the .onDelete method. Let’s walk through an example.

struct ContentView: View {
  @State private var items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]

  var body: some View {
    NavigationStack {
      List {
        ForEach(items, id: \.self) { item in
          Text(item)
        }
        .onDelete(perform: deleteItem)
      }
      .navigationTitle("Swipe to Delete")
    }
  }

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

Your preview should look like this:

Implement swipe-to-delete using the onDelete modifier.
Implement swipe-to-delete using the onDelete modifier.

In this example, you first set up a NavigationStack containing a List. You’ll populate this list using a ForEach loop that iterates through the items array. Each item in the ForEach loop is presented using a Text view.

To implement the swipe-to-delete functionality, you add an .onDelete modifier to ForEach. The .onDelete modifier takes a method that will be called when the swipe-to-delete gesture is performed. In this case, you pass the deleteItem method.

The deleteItem method accepts an IndexSet that contains the indices of the items that are to be deleted. Inside this method, you use the remove(atOffsets:) function to remove these items from the items array.

Now, when you run the app, you can swipe left on an item to reveal a delete button. Tapping the delete button will remove the item from the list.

That’s it! Implementing swipe to delete in SwiftUI is as simple as using the .onDelete method and handling the deletion in the method it calls. This allows you to easily add intuitive item deletion to your lists, enhancing the overall user experience of your app.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.