Flag if scrolling down in tableview

·

2 min read

The indexPath.row is the row that the tableview is currently rendering.

So as you scroll down, the tableview will try to fetch data.

Let's say there are 100 rows in your data, and there are 15 that fit on the screen.

If you don't scroll, then somewhere in your code you can set the lastIndex.

var lastIndex: IndexPath?

lastIndex = indexPath // set this somewhere in the code

So as you scroll down past the first 15 rows, you are asking the tableview to render the data for the next batch of information.

The below code says: are you scrolling down? It knows this because your last index represents 15 rows. But your indexPath.row is asking me to render row 16, so you must be scrolling down.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if let lastIndex = lastIndex, lastIndex.row < indexPath.row {
        // do something if user is scrolling down
    }
    lastIndex = indexPath
}