1

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.

3 Answers3

5

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

Apogee
  • 689
  • 8
  • 19
  • If I want to modify properties of the cell if it is the last cell, should I reloadData or do it int main thread? –  Nov 13 '17 at 12:46
  • Reload the cell. But you need to be careful about the indexPath as it may crash if scrolling and reloading occurs at same time. And for that your dataModel must be updated. – Apogee Nov 13 '17 at 12:51
  • @Balanced Please accept the answer if it helped you to resolve problem that you asked in the question :) – Apogee Nov 13 '17 at 12:53
0

You can try with tableview delegate method:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) 
0

try this code in cell for row method

if indexPath.row == yourarray.count - 1{

                // Put your code

        }
Amul4608
  • 1,390
  • 14
  • 30