I am adding pagination to myTableview
that presents blog posts. The data source is an array of posts, i.e. posts = [post]
.
I initially fetch 20 posts. I have a button that fetches the next 20 records. All of this is working fine. I can't figure how to insert these new records in the table without calling reloadData()
. Can someone explain the following code? I don't understand what going on with the indexPaths
on line 2 and 3 below.
On:
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 items to your tableview, the value passed to insertRows
will be an array of index paths for the new rows in your 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 items in your array, and you add another 20 posts, the 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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With