NEW: Learn SwiftUI with my free YouTube video series! >>

< How to create a list of dynamic items   How to let users move rows in a list >

How to let users delete rows from a list

SwiftUI makes it easy to let users swipe to delete rows by attaching an onDelete(perform:) handler to some or all of your data. This handler needs to have a specific signature that accepts multiples indexes to delete, like this:

func delete(at offsets: IndexSet) {

Inside there you can either loop over every index in the set or just read the first one if that’s the only one you want to handle. Because SwiftUI is watching your state, any changes you make will automatically be reflected in your UI.

Note: The WWDC demonstration for this feature used a non-existent method of Swift arrays called remove(atOffsets:) that does all this work for us – hopefully that will land in a future release.

For example, this code creates a ContentView struct with a list of three items, then attaches an onDelete(perform:) modifier that removes any item from the list:

struct ContentView : View {
    @State var users = ["Paul", "Taylor", "Adele"]

    var body: some View {
        NavigationView {
            List {
                ForEach(users.identified(by: \.self)) { user in
                    Text(user)
                }
                .onDelete(perform: delete)
            }
        }
    }

    func delete(at offsets: IndexSet) {
        if let first = offsets.first {
            users.remove(at: first)
        }
    }
}

If you run that code you’ll find you can swipe to delete any row in the list.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< How to create a list of dynamic items   How to let users move rows in a list >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.0/5

Click here to visit the Hacking with Swift store >>