Reputation:
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.
Upvotes: 1
Views: 8615
Reputation: 719
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
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
And to check for the last row:
if indexPath.row == dataSourceArray.count - 1 {
//Perform action
}
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
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == dataSourceArray.count - 1 {
//Perform action
}
}
You may go through apple docs to know more about tableview delegate methods
Upvotes: 6
Reputation: 1448
try this code in cell for row method
if indexPath.row == yourarray.count - 1{
// Put your code
}
Upvotes: 0
Reputation: 55
You can try with tableview delegate method:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
Upvotes: 0