Don't delete some rows from UITableView

送分小仙女□ 提交于 2021-02-17 02:40:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!