uitableviewdelete-roweditinguitableviewdiffabledatasource

tableView(canEditRowAt) no longer working with tableViewDiffableDataSource


I created a fairly simple tableView for selecting a category for an item model. Everything was working fine yesterday. Today I have been trying to switch the tableView data source over to a UITableViewDiffableDataSource as I want to wrap my head around the API. I have the entire tableView back up and running EXCEPT I can no longer edit my rows!

the setEditing logic works as the newCategoryButton is disabled when I tap the edit button in the navigation bar and is enabled when I tap it again. However, I am never able to swipe to delete and the delete icons do not show up next to my rows in editing mode.

I tried removing setEditing, emptying out commit editingStyle and simply setting canEditRow to return true and still nothing.

Any help would be greatly appreciate. Thank!

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    let section = dataSource.snapshot().sectionIdentifiers[indexPath.section]
    if section == .noneSelected {
        return false
    } else {
    return true
    }
}

override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: true)
    if editing == true {
        newCategoryButton.isEnabled = false
    } else {
        newCategoryButton.isEnabled = true
    }
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        categories.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let movedCategory = categories.remove(at: sourceIndexPath.row)
    categories.insert(movedCategory, at: destinationIndexPath.row)
}

screenShot after edit button is tapped


Solution

  • The trouble is that canEditRowAt is a data source method. You (the view controller) are now not the data source; the diffable data source is. You need to implement this method inside the diffable data source. That's typically done by subclassing the diffable data source class, so that you can override this method. Otherwise, the diffable data source just returns its default value — which is false, which is why you currently can't edit any rows.