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]]
While I have attempted to answer the question, it should be noted that in 2019, Apple introduced a new pattern called “diffable data sources”. See WWDC 2019 video Advances in UI Data Sources and 2020’s Advances in diffable data sources. These completely eliminate the need to manually add items to a table view. One just updates the model, and then updates the “snapshot”, and the OS takes care of adding and removing of the individual cells for you. It will feel foreign the first time you use it, but once you go diffable, you will never go back. It makes life so much easier.
Note, these videos discuss both diffable data sources and composable layouts. While both greatly improve the table/collection view programming (and user) experience, you can tackle them separately. First, get your arms around the diffable data sources. You can tackle the composable layouts later.
row
values inIndexPath
are zero-based, the first new row (row 21) would be anIndexPath
with arow
of20
and the last one would have arow
of39
, for a total array of 20 new index paths. – SepticidalbeginUpdates
andendUpdates
if you're doing multiple calls to update cells and you want them all to take place in one update. Since you're only doing one call toinsertRows
, nobeginUpdates
andendUpdates
is needed. It doesn't hurt, but it's just not needed. – Septicidal