在UITableView中使用insertRow进行Swift无效更新

在UITableView中使用insertRow进行Swift无效更新,swift,asynchronous,insert,tableview,Swift,Asynchronous,Insert,Tableview,我受够了。我正在使用async func从servevr加载数据 APIManager.loadBlocks(block_name: block_name, offset: indexPath.row + 1) { ( blocks, error) in if error == nil { DispatchQueue.main.async { tableView.beginUpdate

我受够了。我正在使用async func从servevr加载数据

        APIManager.loadBlocks(block_name: block_name, offset: indexPath.row + 1) { ( blocks, error) in
            if error == nil {
                DispatchQueue.main.async {
                    tableView.beginUpdates()
                    self.currentBlock.items.append(contentsOf: blocks![0].items)
                    tableView.insertRows(at: [IndexPath(row: self.currentBlock.items.count - 1, section: 0)], with: .automatic)
                    tableView.endUpdates()
                    spinner.stopAnimating()
                    tableView.tableFooterView?.isHidden = true
                }
            }
        }
我有

无效更新:节0中的行数无效。更新(20)后现有节中包含的行数必须等于更新(10)前该节中包含的行数,加上或减去从该节中插入或删除的行数(插入1行,删除0行),加上或减去移入或移出该节的行数(0移入,0移出)。”

我已经测试了加载块完成前后currentBlock.items的计数。这是正确的:10个之前,20个之后。但是为什么10个附加项的计数与错误输出中插入的1相同

我试过使用tableView.reloadData()-它可以工作,但我需要一个正常的插入动画

我也试过了

for item in blocks![0].items {
self.currentBlock.items.append(item)
}


仍然不起作用

您似乎只插入了一行,但您正在使用
append(contentsOf:)
向模型中追加10项

插入的行数应与附加模型的行数相同。插入行的索引为:

self.currentBlock.items.count
self.currentBlock.items.count + 1
self.currentBlock.items.count + 2
self.currentBlock.items.count + 3
...
self.currentBlock.items.count + blocks![0].items.count - 1
(请注意,
self.currentBlock.items.count
是插入新型号之前的值)

您可以创建包含上述行的索引路径数组,如下所示:

let indexPathsToInsertRows = (0..<blocks![0].items.count).map { 
    IndexPath(row: self.currentBlock.items.count + $0, section: 0)
}
并在我们刚刚计算的索引路径处插入行:

tableView.insertRows(at: indexPathsToInsertRows, with: .automatic)
self.currentBlock.items.append(contentsOf: blocks![0].items)
tableView.insertRows(at: indexPathsToInsertRows, with: .automatic)