How do you enable editing (e.g., deletion) in a `UITableView`?

iOS interview question for Intermediate practice.

Answer

To enable editing, specifically row deletion via the standard swipe-to-delete gesture or Edit mode in a UITableView, you need to implement two key methods in your UITableViewDataSource: 1. tableView(:commit:forRowAt:): Purpose: This method is called when the user commits an editing action (like tapping the 'Delete' button after swiping). Implementation: Inside this method, you check if the editingStyle is .delete. If it is, you must: Update Data Source: Remove the corresponding data item from your underlying data model (e.g., remove element from array). Update Table View: Tell the table view to remove the row visually using tableView.deleteRows(at: [indexPath], with: .automatic) (or other animation style). swift func tableView( tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { print("Deleting row \(indexPath.row)") // 1. Update data source items.remove(at: indexPath.row) // 2. Update table view visually tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Handle insertion if needed } } 2. tableView(:canEditRowAt:) - Bool (Optional but Recommended): Purpose: Determines if a specific row can be edited. While optional (defaults to true if commit:forRowAt: is implemented), it's good practice to implement it for fine-grained control. Implementation: Return true for rows that should be editable (allow swipe-to-delete/show editing controls), and false for those that shouldn't. swift func tableView( tableView: UITableView, canEditRowAt indexPath: IndexPath) - Bool { // Example: Allow editing for all rows return true // Example: Disallow editing for the first row // return indexPath.row != 0 } By implementing tableView(:commit:forRowAt:) and handling the .delete case (which involves updating both the data source and the table view), you enable the standard deletion functionality.

Explanation

You can toggle the table view's editing mode programmatically by setting its isEditing property, often triggered by an 'Edit'/'Done' button in the navigation bar.

Related Questions