How to delete a cell by tapping a button in SwiftUI

joker hook
Sep 10, 2019 · 4 min read
Photo by Jeremy Bishop on Unsplash

Apple has been launching SwiftUI for a while, and I’m also learning about SwiftUI and benefiting a lot.

Some time ago, I have been learning about list. I learned about the details of how SwiftUI handles List by learning the video of WWDC19. But it is a pity that WWDC videos only provide a way to slide the delete cell, but what I want to achieve is to delete the cell by clicking a button on the cell.

Obviously, the method of sliding to delete a cell is suitable for the table views that their cell’s height is not too tall, like the Mail app and Message app.

However, if the application you are designing is similar to Twitter or Instagram, the sliding delete method is not appropriate. Obviously, if you use the sliding delete operation in a highly high cell, then the human-computer interaction is too bad.

We can see that both Twitter and Instagram provide a button to choose from in the upper right corner. When you press the button, a pop-up window will pop up. In this interface, you can perform a series of operations. This method completely replaces the traditional sliding delete operation, making human-computer interaction more friendly.

This is the function we will implement next. As you can see, when we click the delete button, the corresponding cell will be deleted.

Maybe you will say that this is very simple. In Swift, you only need to get the indexPath corresponding to the cell.

But since Apple has released SwiftUI, we can use SwiftUI to achieve it.

Create a form interface

First, you need to create a new single view application.

And then create a Swift file, I named it Data.swift, then add a struct in the file.

import SwiftUIstruct Music: Identifiable, Hashable {
var id = UUID()
var name: String
}

We will use the id attribute later. It’s very important, every cell we create needs an id.

Open your ContentView.swift, and add the code in the view(above the body view).

@State var musicLists = [
Music(name:"THE GIFT"),Music(name:"Something Just Like This"),
Music(name:"Dream It Possible"),
Music(name:"Eyes On Me"),
Music(name:"Windy Hill"),
Music(name:"LOVE Theme from TIGA"),
Music(name:"Victory"),
Music(name:"Bamboo"),
Music(name:"Summer")
]

Here we have created a data source, which we will use later in the list.

Then, in the body view, add our navigation view and list view:

NavigationView {
List {
ForEach(musicLists) { music in
HStack {
Text(music.name)
Spacer()
Button(action: {}){
Text("Delete")
}.foregroundColor(Color(.red))
}
}
}.navigationBarTitle("Songs")
}

If you have doubts about this code, I highly recommend that you take a look at the WWDC video or Apple’s SwiftUI tutorial, you will understand, because it is very simple.

After adding the above code, you will see in the Canvas that the list has been created.

Implement the method of deleting the cell

Now we have to implement the delete function, which is also very simple.

In fact, the principle of deleting a cell is roughly to find the index of the cell corresponding to the click button, and then delete the element of the corresponding position in the data source.

Declare a method outside the body view:

func delete(at index: Int) {
musicLists.remove(at: index)
}

Yes, you are not mistaken, this method is as simple as that, no need to add other content.

Add this method to the action of the button.

Button(action: { self.delete(at:)}) {
···
}

The question we are facing now is what should be written after the ‘at’. Remember our id attribute? The advantage of the id attribute at this time is reflected.

Use the method of firstIndex, it’s powerful.

Button(action: { self.delete(at:self.musicLists.firstIndex(where: { $0.id == music.id })!)}) {
···
}

We’re done, we can now run the project in Canvas, and you’ll see that everything is perfect.

Thanks to SwiftUI, we are able to implement complex functions with less code.

The Startup

Get smarter at building your thing. Join The Startup’s +788K followers.

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

joker hook

Written by

👨‍🎓/study communication engineering🛠/love iOS development💻/🐶🌤🍽🏸🏫

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

joker hook

Written by

👨‍🎓/study communication engineering🛠/love iOS development💻/🐶🌤🍽🏸🏫

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store