How to implement TableView.insertRows
I am adding a pagination to myTableview
that represents blog posts. The data source is an array of messages, i.e. posts = [post]
...
I initially collect 20 posts. I have a button that fetches the next 20 records. This all works fine. I cannot figure out how to insert these new records into the table without calling reloadData()
. Can anyone explain the following code? I don't understand what is going on with indexPaths
in lines 2 and 3 below. ABOUT:
IndexPath(row:(self.posts.count - 1)
Am I passing the last row of the original dataset or the updated one?
TableView.beginUpdates()
let indexPath:IndexPath = IndexPath(row:(self.posts.count - 1), section:0)
TableView.insertRows(at: [indexPath], with: .left)
TableView.endUpdates()
If you want to add elements to the table, the value passed to insertRows
will be an array of index paths for new rows in the model object:
let additionalPosts = ...
posts += additionalPosts
let indexPaths = (posts.count - additionalPosts.count ..< posts.count)
.map { IndexPath(row: $0, section: 0) }
tableView.insertRows(at: indexPaths, with: .left)
So, if you had 20 elements in your array and added 20 more posts, it indexPaths
would be:
[[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]]