编辑 UITableView 出现的错误

来源:互联网 发布:幼儿美工室活动记录 编辑:程序博客网 时间:2024/05/29 03:45

‘Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), 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).’

意思就是说,在你删除一行的时候,没有更新 tableView 对应的
tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
这个方法。

这是很合情合理的。假如你有 8 行的一个列表,和一个含有 8 个元素的数组。这个数组就是这个列表的源。在你删除了一行后,这时列表需要刷新(自动),这时会请求这个列表的行数,返回的还是 8,跟现在的行数 7 并不对应。
原因是在你删除了一行后,没有删除相应的源数组的数据,导致列表在询问行数的时候得到的还是 8,跟现在的 7 冲突,才会出现这个错误,所以在删除行的前面先把数据删除。

    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {        let deleteRow = UITableViewRowAction(style: .destructive,                                             title: "Del") { (deleteRow, indexPath) in                                                self.lotteries.remove(at: indexPath.row) // 先删除数据                                                tableView.deleteRows(at: [indexPath], with: .right) // 再删除行        }        return [deleteRow]    }
原创粉丝点击