ios - 无法从 TableView 中删除行

标签 ios swift xcode

我有一个包含一定行数的 TableView 。使用同一个 ViewController 上的按钮,我想弹出 tableView 行之一。但是,我无法这样做。请注意,我没有使用表格 View 的编辑样式,而是使用同一个 ViewController 上的按钮从 tableView 中删除一行。

func postAction() {
        postTable.deleteRows(at: [IndexPath(row: 0, section: 0)] , with: .fade)
}

但是这会导致崩溃。我不确定为什么会发生这种情况以及我应该如何纠正它。我打算从 tableView (postTable) 的唯一部分中删除第一行

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.
The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

我的代码:

    postTable.delegate = self
    postTable.dataSource = self

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 3
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = JobPostCellView(style: UITableViewCellStyle.default , reuseIdentifier: "PostCell")
            cell.delegate = self
            cell.name = arr[indexPath.row]
            return cell
    }

最佳答案

试试这个

func postAction() {
    let indexPath = IndexPath(row: 0, section: 0)
    yourmodel.remove(at: indexPath.row)//update your model also here
    postTable.deleteRows(at: [indexPath] , with: .fade)
}

这可能会发生,因为您的 TableView 行与数据源的部分方法中行数的返回行不匹配

例如

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

如果您在 numberOfRowsInSection 中返回 10,那么表中将有 10 行

现在您要从中删除 1 行,因此行数将为 9,但您的 numberOfRowsInSection 方法仍返回 10,因此这会造成不一致,因此您必须更新 numberOfRowsInSection 部分中的计数以返回 9

如果你使用的是动态数组,那么你必须将它从你的数组中删除,就像在答案中一样

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

相关文章:

ios - 在 Swift3 中发送 JSON POST 请求

ios - 从字典创建 Swift 对象

swift - 从 [AnyHashable :URL] 类型的 Swift 字典中获取值

ios - 动态调整今天的小部件

iphone - 从 ViewController 设置 UIImageView 图像

iphone - 单个对象,多个 IBOutlets

ios - 当用户快速移动时,SKSpriteNode 移出父级边界的问题

json - 从 JSON 数据向 TableView 添加部分

iOS:无法编译连接:Cell 中的 UIImageView

ios - Flex 4.6 TextInput 提示 ios 行为不当