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.
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? { }
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? { }
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])
}
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.
Top comments (0)