更新无效:第0部分中的行数无效,更新后现有部分中包含的行数

时间:2019-03-01 14:10:16

标签: swift uitableview delete-row

滑动并删除UITableCell

时,我总是收到此错误消息
  

由于未捕获的异常而终止应用程序   NSInternalInconsistencyException,原因:无效的更新:无效   第0节中的行数。   更新(11)之后的现有部分必须等于   更新(11)之前该部分中包含的行,正负   从该部分插入或删除的行数(已插入0,   1个已删除),加上或减去移入或移出的行数   该部分(0移入,0移出)。

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = deleteAction(at: indexPath)
    tableView.reloadData()
    print(listOfCoins)
    print(listOfCoins.count)
    return UISwipeActionsConfiguration(actions: [delete])
}

func deleteAction(at indexPath: IndexPath) -> UIContextualAction {
    let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, nil) in
        self.listOfCoins.remove(at: indexPath.row)
       self.tableView.deleteRows(at: [indexPath], with: .automatic)
        self.tableView.reloadData()
        }
    action.title = "Delete"
    action.backgroundColor = .red
    return action
}

我尝试取出“ self.tableView.deleteRows”,它允许应用程序运行并从我的源中删除indexPath,但是我不知道为什么当'tableView.reloadData()时单元格不会消失之后被称为。

enter image description here

1 个答案:

答案 0 :(得分:1)

您只需要

self.listOfCoins.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .automatic)

所以删除此

let delete = deleteAction(at: indexPath)
tableView.reloadData() // remove this line

self.tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableView.reloadData() // remove this line

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = deleteAction(at: indexPath) 
    print(listOfCoins)
    print(listOfCoins.count)
    return UISwipeActionsConfiguration(actions: [delete])
}

func deleteAction(at indexPath: IndexPath) -> UIContextualAction {
    let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, nil) in
        self.listOfCoins.remove(at: indexPath.row)
        self.tableView.deleteRows(at: [indexPath], with: .automatic) 
    }
    action.title = "Delete"
    action.backgroundColor = .red
    return action
}