Swift and SwiftUI tutorials for Swift Developers

Swipe to Delete in SwiftUI

In this tutorial we will see how to implement Swipe to Delete in SwiftUI, that is, how we can let users delete rows from a list.

In mobile app development, it is a common requirement to give users the ability to delete items from a list, which is often achieved with a swipe to delete gesture. In SwiftUI, this functionality is easy to add with the .onDelete modifier.

Let’s look at an example:

@State private var users = ["Paul", "Taylor", "Adele"]

    var body: some View {
        NavigationStack {
            List {
                ForEach(users, id: \.self) { user in
                    Text(user)
                }
                .onDelete { (IndexSet) in
                
                    self.users.remove(atOffsets: IndexSet)
                }            }
            .navigationTitle("Users")
        }
    }

In this example we first set up a NavigationStack that contains a List. You will populate this list using a ForEach loop that loops through the array of items. Each item in the ForEach loop is presented using a text view.

To implement the swipe-to-delete functionality, we add the .onDelete modifier to ForEach.

In the onDelete closure, we pass an indexSet that contains the index of the rows that need to be deleted. We then call the remove method with the indexSet to delete specific items in the users array.

Note that every time the user deletes a row from the list, the UI should be updated. Note that we use the @State keyword in SwiftUI to notify SwiftUI that it should monitor the property and update the UI whenever the property value changes.

Now, when you run the app, you can swipe left on an item to bring up a Delete button. Pressing the Delete button will remove the item from the list.

On the other hand, have you noticed the nice animation that happens when a row is deleted? You don’t need to write any extra code. This animation is automatically generated by SwiftUI.

Leave a Reply

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

Previous Article

How to create a Stepper in SwiftUI

Next Article

How to show an Action Sheet in SwiftUI

Related Posts