I use the idea of custom TableView pagination using willDisplayCell (or cellForRowAt) and updates from the server.
And the problem is that willDisplay called even for cells that are not on the screen.
How can I handle this behavior and change the flow to update cells only when user get scrolled to the last cell?
private func isLoadingIndexPath(_ indexPath: IndexPath) -> Bool {
return indexPath.row == self.orders.count - 1
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// fetch new data if user scroll to the last cell
guard isLoadingIndexPath(indexPath) else { return }
if self.totalItems > orders.count {
fetchNextPage()
}
}
private func fetchNextPage() {
self.currentPage += 1
self.delegate?.didReachLastCell(page: currentPage)
}
didReachLastCell calls the addOrders:
func addOrders(_ orders: [OrderView]) {
self.orders.append(contentsOf: orders)
reloadOrders()
}
fileprivate func reloadOrders() {
self.tableView.reloadData()
}
Note: The same problem is reproducible for cellForRowAt method too.
I had this problem when using UITableView.automaticDimension
for cell height. I solved this problem using a higher value for estimatedRowHeight
property.
Something like this:
tableView.estimatedRowHeight = 1000
Now willDisplay
will be called only for rows which are visible.
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