TableView Row Swipe Action

iOS Dev
3 min readSep 8, 2021

Not often but sometimes you have to implement row swipes in your project. And I want to share one of the methods with you. I continue my small project from the previous article(POP UITableView). Well, let’s start.

First of all we need an item with which we can set up our swipe buttons. For this purpose, create a protocol (Picture #1):

Picture #1

What I like here that we can choose enum, struct etc. That can give us flexibility, depending on task.

Picture #2

Let’s implement next protocol (Picture #2). It’s also very simple, it consists of two functions and one associated type property. We can do some default setup here.

Picture #3

Like it`s shown in “Picture #3”, functions in the extension create and set up UIContextualActions for tableView. So, we've almost finished. Further we create a file, give it a preferable name (I called it ContextualActionManager) and put all code above into the file (Picture #4).

Picture #4

Now add contextual swipe to our controller. We have to make several steps for this.

Step#1. Create a contextual item (I chose enum, in my oppinion it will be handful here), implement ContextualItemConfigurable protocol and set up all nesessary info (Picture #5).

Picture #5

Step#2. Create a protocol RowContexable (Picture #6). We have 3 models inside the project: AnimalModel, HostModel, EquipmentModel. And we want, for instance, to have a swipe only for AnimalModel and EquipmentModel.

Picture #6

That`s very easy. Implement RowContextable protocol for models where you wish to have a contextual swipe. And for “actions” property, set up what kind of actions you want, like in “Picture #7” below:

Picture #7

Step #3. Implement ContextualActionManagable protocol to our controller (Picture #8).

Picture #8

Set up our ContextualItem and implement action handler (Picture #9).

Picture #9

And the last but not the least step is to add trailingSwipeActionsConfigurationForRowAt function to UITableDataSource like “Picture #10” shows.

That`s all. We did it. How do you work with Contextual swipes? Feel free to give your tips and hints in comments.

--

--