ios - 无法删除 tableView 中的行

标签 ios swift uitableview

我不断收到一条错误消息,提示 无效更新:第 0 部分中的行数无效。更新 (2) 后现有部分中包含的行数必须等于该部分中包含的行数更新前 (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
    }

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

@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)
    }

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

最佳答案

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)
}

关于ios - 无法删除 tableView 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848556/

相关文章:

ios - 如何在 React Native 中更改 "Bundle Identifier"?

iphone - 拒绝后重新提交ios应用程序

ios - CMDeviceMotion 的磁场属性不正确?

ios - 更改 SCNNode 比例无效

ios - 如何在iOS中重新加载 TableView Controller 中的数据?

ios - Iphone 桌面 View

ios - GluonVM 在 iOS 设备上启动 [问题]

ios - 重写后总是调用 super?

swift - 如果 UITextView.contentSize.height 在 Swift 中不可编辑或滚动启用,为什么它不起作用?

iphone - UITableViewCell 动画