问题
I'm trying to implement the functionality to delete some rows from a table view
and not others. In this case, everything in section 0
should not be deletable (so not swipe to delete either), but everything in section 1
should be able to. How can I implement this? Currently section 0
rows cannot delete, but when the user swipes, the delete action still appears.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (indexPath.section == 0){
// dont delete the rows
} else {
if (editingStyle == .delete){
let fetchRequest: NSFetchRequest<Conversions> = Conversions.fetchRequest()
do {
let result = try PersistenceService.context.fetch(fetchRequest)
// Delete from CoreData and remove from the array
if (result.contains(allConversions[indexPath.row])){
PersistenceService.context.delete(allConversions[indexPath.row])
allConversions = allConversions.filter { $0 != allConversions[indexPath.row] }
PersistenceService.saveContext()
self.tableView.reloadData()
}
} catch {
print(error.localizedDescription)
}
}
}
回答1:
UITableView
has a method exactly for this purpose called canEditRowAt
. You just need to return false when indexPath.section == 0
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return indexPath.section != 0
}
来源:https://stackoverflow.com/questions/60468292/dont-delete-some-rows-from-uitableview