首页 > 解决方案 > 无法删除 tableView 中的行

问题描述

我不断收到错误消息Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2)。我有一个带有部分的 tableView,每个部分都包含一个表示行的字符串数组。我还尝试通过添加到 cellforRowAt 上的单元格的按钮进行删除。

extension RequestsViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArr[section].myItems.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RequestViewCell", for: indexPath) as! RequestViewCell

        cell.description.text = "\(myArr[indexPath.section].myItems[indexPath.row])"
        cell.declineBtn.tag = (indexPath.section * 100) + indexPath.row
        cell.declineBtn.addTarget(self, action: #selector(declineRequest(sender:)), for: .touchUpInside)
        cell.acceptBtn.tag = (indexPath.section * 100) + indexPath.row
        cell.acceptBtn.addTarget(self, action: #selector(acceptRequest(sender:)), for: .touchUpInside)

        return cell
    }

然后如果按下拒绝 btn,则被调用的方法应该删除该行

@objc func declineRequest(sender: UIButton) {
        let section = sender.tag / 100
        let row = sender.tag % 100
        let indexPath = IndexPath(row: row, section: section)

        myArr.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }

我尝试将协议方法也“提交编辑样式”添加到 .delete 和 canEditRowAt,但没有运气,因为我遇到了同样的错误。

标签: iosswiftuitableview

解决方案


declineRequest你必须删除

myArr[section].myItems.remove(at: row)

如果您还想删除项目数组变为空的部分,请写入

// if there is one item left delete the section (including the row)
if myArr[section].myItems.count == 1 {
    myArr.remove(at: section)
    tableView.deleteSections([section], with: .fade)
} else { // otherwise delete the row
    myArr[section].myItems.remove(at: row)
    tableView.deleteRows(at: [indexPath], with: .fade)
}

推荐阅读