Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TableView willDisplayCell called for cells that are not on the screen (tableView pagination)

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.

like image 394
atereshkov Avatar asked Jan 07 '18 11:01

atereshkov


1 Answers

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.

like image 107
Mukesh Avatar answered Sep 16 '22 11:09

Mukesh