编辑 UITableView 出现的错误

‘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]
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十月ooOO

许个愿,我帮你实现

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值