我正在为 myTableview
添加分页显示博客文章。数据源是一个帖子数组,即 posts = [post]
.
我最初获取了 20 个帖子。我有一个按钮可以获取接下来的 20 条记录。所有这些都运行良好。我不知道如何在不调用 reloadData()
的情况下在表中插入这些新记录.有人可以解释以下代码吗?我不明白 indexPaths
发生了什么事情在下面的第 2 行和第 3 行。
在:
IndexPath(row:(self.posts.count - 1)
我是通过原始数据集的最后一行还是更新后的数据集?
TableView.beginUpdates()
let indexPath:IndexPath = IndexPath(row:(self.posts.count - 1), section:0)
TableView.insertRows(at: [indexPath], with: .left)
TableView.endUpdates()
最佳答案
如果您想向 tableview 添加项目,则传递给 insertRows
的值将是模型对象中新行的索引路径数组:
let additionalPosts = ...
posts += additionalPosts
let indexPaths = (posts.count - additionalPosts.count ..< posts.count)
.map { IndexPath(row: $0, section: 0) }
tableView.insertRows(at: indexPaths, with: .left)
因此,如果您的数组中有 20 个项目,并且您又添加了 20 个帖子,则
indexPaths
将是:[[0, 20], [0, 21], [0, 22], [0, 23], [0, 24], [0, 25], [0, 26], [0, 27], [0, 28], [0, 29], [0, 30], [0, 31], [0, 32], [0, 33], [0, 34], [0, 35], [0, 36], [0, 37], [0, 38], [0, 39]]
关于uitableview - 如何实现 TableView.insertRows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43453220/