I have a UITableView
that lists out data from an api.
Currently those responses are batched in groups of 50 items.
To support 'infinite scrolling' I currently do something like this
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == items.count - 1 && !isPaginating {
requestNextPage()
}
}
When requestNextPage
completes, I update the array on my view model and then call
func reloadTableView() -> Void {
DispatchQueue.main.async {
self.activity.stopAnimating()
self.tableView?.reloadData()
}
}
which essentially reloads the table, rendering the new rows added to my array by requestNextPage
.
I don't like this approach as it causes the whole table to be reloaded and feels a bit......clunky.
I was thinking perhaps it is better to do this with insertRowsAtIndexPaths
but I am not sure how I can achieve this.
I tried something like
var indexPaths = [IndexPath]()
for i in self.items.count...self.items.count + feed.count {
indexPaths.append(IndexPath(row: i, section: 0))
}
self.insertNewRows?(indexPaths)
Which I hoped would take the existing row count items.count
and add my new rows feed.count
and then let me call insertNewRows
which essentially triggers this in my view
func insertRows(_ indexPaths: [IndexPath]) {
tableView?.beginUpdates()
tableView?.insertRows(at: indexPaths, with: .fade)
tableView?.endUpdates()
}
Is it possible to create an infinite scroll effect in this manor? My current approach triggers an exception
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 50 into section 0, but there are only 50 rows in section 0 after the update'
I am using Swift, so Objective C answers are proving difficult to follow, and I would prefer not to install a 3rd party library to handle this.
The 'duplicate' question also recommend a lib that has not been updated in 7 years.