无法在表格视图中插入行

米沙(Misha Timofeev)

我阅读了有关此问题的所有相关文章,但仍然出现错误:

'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (13) must be equal to the number of rows contained in that section before the update (13), plus or minus the number of rows inserted or deleted from that section (11 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

这是代码:

func appendItems(entities: [Entity]) {
    if entities.count > 0 {
        let entitesFirstPos = items.count
        self.items.append(contentsOf: entities)
        var indexPaths: [IndexPath] = []
        for i in entitesFirstPos..<items.count {
            indexPaths.append(IndexPath(row: i, section: 0))
        }

        self.tableView.beginUpdates()
        self.tableView.insertRows(at: indexPaths, with: .none)
        self.tableView.endUpdates()
    }
}
弗雷

看起来appendItems()是UITableViewController的子类中的函数。如果是这种情况,请尝试以下方法。如果不知道tableView(UITableView,numberOfRowsInSection:Int)和tableView(UITableView,cellForRowAt:IndexPath)的外观,就不可能给出确切的答案。因此,这是基于以下假设:self.items只是一个数组,其中包含第0节中所有单元的数据。

首先尝试进行此更改:

//self.tableView.beginUpdates()
//self.tableView.insertRows(at: indexPaths, with: .none)
//self.tableView.endUpdates()
self.tableView.reloadData()

进行此更改将更新您的表格视图,而无需为所有新行批量执行行插入动画。如果可行,您的问题就在appendItems()函数中。在这种情况下,请尝试进行以下更改:

func appendItems(entities: [Entity]) {
    if entities.count > 0 {
        self.tableView.beginUpdates() // <--- Insert this here
        let entitesFirstPos = items.count
        self.items.append(contentsOf: entities)
        var indexPaths: [IndexPath] = []
        for i in entitesFirstPos..<items.count {
            indexPaths.append(IndexPath(row: i, section: 0))
        }

        //The following line is now at the top of the block.
        //self.tableView.beginUpdates() 
        self.tableView.insertRows(at: indexPaths, with: .none)
        self.tableView.endUpdates()
    }
}

进行此更改将确保,如果在调用beginUpdates()函数之前由UITableView查询某个节中的行数,或者甚至由该函数本身来查询,则将返回正确的行数。在当前设置,假设self.items代表表视图数据,行的更新数量将beginUpdates之前已经显现()被调用。如果这不起作用,则需要更多代码来查明问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章