DEV Community

Cover image for Swipe actions in UITableViewCell
Berkay Oruç
Berkay Oruç

Posted on

Swipe actions in UITableViewCell

Swipe in mail

Introduction

The feature that comes with iOS 11 can be defined as left to right (leading) or right to left (trailing). Basically, we create swipe operations that we can give .normal and .destructive styles in UIContextualAction. We can create more than one UIContextualAction class that takes style, title and handler parameters and use it for the related swipe operation. Without further talking, let's write some code.

Coding cat

Let's Code

First, I assume we have already defined a UITableView. We use the following code to add a swipe action to the beginning of the UITableViewCell.

override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { }
Enter fullscreen mode Exit fullscreen mode

On the contrary, in order to add the swipe operation to the end of the UITableViewCell, we need to add the trailing state to our code.

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { }
Enter fullscreen mode Exit fullscreen mode

Now let's fill in these functions. I'm sure you've noticed. Our functions require optional UISwipeActionsConfiguration as a return type. Here, we can define multiple actions for trailing or leading swipe operations, thanks to the parameter type Swift provides us.

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
   let favouriteaction = UIContextualAction(style: .normal, title: "Edit") { [weak self] (action, view, completionHandler) in
      self?.handleMarkAsFavourite()
      completionHandler(true)
   }
   favouriteaction.backgroundColor = .systemBlue
   let deleteaction = UIContextualAction(style: .destructive, title: "Delete") { [weak self] (action, view, completionHandler) in
      self?.handleMoveToTrash(index: indexPath.row)
      completionHandler(true)
   }
   deleteaction.backgroundColor = .systemRed
   return UISwipeActionsConfiguration(actions: [favouriteaction, deleteaction])
}
Enter fullscreen mode Exit fullscreen mode

Swipe result gif

Last Words

In this article, I tried to explain how we can define swipe operations that are indispensable for UITableViewCell. I hope this article will enrich your applications a little more. Happy days everyone.

References

Latest comments (0)