I am trying to achieve a custom action on the last row of my UITableView.
I found a nice extension in order to know if I'm on the last row :
extension UITableView {
func isLast(for indexPath: IndexPath) -> Bool {
let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1
return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
}
}
The only issue I'm facing is that if my tableView has many rows, with scrollable content, the last row isn't visible.
Thus, in my cellForRow I am doing this :
if tableView.isLast(for: indexPath) {
print("Last Row - Do Specific action")
} else {
}
It is working, except that imagine my screen can display 6 rows, but the total number of rows of my tableView is 15.
It will apply my specific action on the row at indexPath 5 and 15.
I am guessing it is because each time cellForRow is called, it is checking for the last row, and it apply on the last visible row also.
How can I achieve a custom action ONLY on the last row even if it is not visible yet?
EDIT: After more investigation, the issue comes from UITableView not able to prefetch the cell, and cellLoaded and cellVisible is the same.
Best Answer
I can't copy paste the code as I don't have xcode right now.
But if you want to perform action before cell gets displayed then do it in
And to check for the last row:
dataSourceArray is the array from which you are fetching the data to show it in the cell.
Basically your code should be something like this
You may go through apple docs to know more about tableview delegate methods