UITableViewCell
iOS Development
Swipe Actions
Delete Button
Swift Programming

UITableViewCell, show delete button on swipe

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

UITableViewCell is a fundamental component in iOS development, particularly when working with UITableView. This component defines the characteristics and functionality of a single row in a table view. It's important for creating interactive and dynamic table views in iOS applications. One common feature in many apps is the ability to delete a table row using a swipe gesture. This functionality is user-friendly, quick, and aligns with standard iOS design guidelines.

Understanding UITableViewCell

A UITableViewCell object is a specialized view that can contain a single cell's content, such as text, images, or other custom views. It's essential to create customized UITableViewCell objects for your table view to display data dynamically and interactively.

Anatomy of UITableViewCell

A UITableViewCell has multiple parts:

  • Content View: The primary container for a cell's content.
  • Text Label: A default UILabel for displaying text.
  • Detail Text Label: An optional UILabel for additional text.
  • Image View: An optional UIImageView for displaying images.
  • Accessory View: An optional view that appears at the right side of the cell and indicates a detailed view is available or provides additional actions.

Implementing the Swipe-to-Delete Feature

Implementing the swipe-to-delete feature in a UITableViewCell involves using the UITableViewDelegate methods to manage the editing actions. Here’s a step-by-step guide to implementing this feature.

Step 1: Enable Editing

First, ensure that the UITableView is editable by setting it to true:

swift
self.tableView.isEditing = true

Step 2: Implement editingStyleForRowAt

To enable the delete functionality, implement the tableView(_:editingStyleForRowAt:) method. This method asks the delegate for the editing style for a specific row.

swift
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .delete
}

Step 3: Handle the Deletion

Next, handle the actual deletion of the data and update the table view using tableView(_:commit:forRowAt:). This method will remove the data source’s entry and update the table view.

swift
1func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
2    if editingStyle == .delete {
3        dataSource.remove(at: indexPath.row)
4        tableView.deleteRows(at: [indexPath], with: .fade)
5    }
6}

Step 4: Optional Custom Actions

You can customize the swipe actions further by implementing tableView(_:leadingSwipeActionsConfigurationForRowAt:) or tableView(_:trailingSwipeActionsConfigurationForRowAt:). These methods allow for more customization by providing alternative actions or modifying the appearance of the swipe actions.

swift
1func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
2    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (_, _, completionHandler) in
3        self.dataSource.remove(at: indexPath.row)
4        tableView.deleteRows(at: [indexPath], with: .automatic)
5        completionHandler(true)
6    }
7    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
8    configuration.performsFirstActionWithFullSwipe = false
9    return configuration
10}

Advanced Customizations

Custom UITableViewCell

For more complex designs, you may need to create a custom subclass of UITableViewCell. This involves designing a custom .xib file or setting up UI elements programmatically.

swift
1class CustomTableViewCell: UITableViewCell {
2    @IBOutlet weak var customLabel: UILabel!
3    @IBOutlet weak var customImageView: UIImageView!
4    
5    override func awakeFromNib() {
6        super.awakeFromNib()
7        // Initialization code
8    }
9}

Autolayout Considerations

When designing custom cells, remember to use Auto Layout constraints to ensure that your UI elements adjust properly when devices rotate or change size classes.

Asynchronous Loading

If your cell displays images or loads data asynchronously, ensure that these tasks do not block the main thread. Use GCD or other asynchronous mechanisms to handle these tasks.

swift
1DispatchQueue.global().async {
2    let imageData = try? Data(contentsOf: imageURL)
3    DispatchQueue.main.async {
4        if let data = imageData {
5            cell.customImageView.image = UIImage(data: data)
6        }
7    }
8}

Summary of UITableViewCell and Swipe-to-Delete

Key ConceptDescription
UITableViewCellA class for creating table view cells, containing content.
Content ViewPrimary container for cell's content, including text, images, etc.
Default PropertiesIncludes textLabel, detailTextLabel, imageView, accessoryView.
Swipe-to-DeleteImplemented using UITableViewDelegate methods for ease of use.
Editing StyleDetermines if a cell is editable, typically .none, .delete, or .insert.
tableView(_:commit:forRowAt:)Method for committing editing actions such as deletions.
Custom ActionsMore actions on swipe using UISwipeActionsConfiguration.
Custom CellsCustom UITableViewCell subclass for complex designs.
Asynchronous TasksEnsure images/data loading does not block the main thread with GCD.

Conclusion

The implementation of UITableViewCell and the swipe-to-delete feature enhances user interaction and aligns with modern iOS application design principles. By leveraging the powerful API of UITableView and UITableViewCell, developers can create dynamic and engaging applications that are efficient and intuitive to use.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.