iOS - How can I get the IndexPath of the last item in a tableview?

Solution 1:

To get a reference to the last row in the last section…

// First figure out how many sections there are
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;

// Then grab the number of rows in the last section
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;

// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];

Solution 2:

You can get the indexPath of the last row in last section like this.

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)];

Here, numberOfSections is the value you return from numberOfSectionsInTableView: method. And, numberOfRowsInLastSection is the value you return from numberOfRowsInSection: method for the last section in the table view.

This can be placed in a subclass or category to make it easy:

-(NSIndexPath*)indexPathForLastRow
{
    return [NSIndexPath indexPathForRow:[self numberOfRowsInSection:self.numberOfSections - 1] - 1 inSection:self.numberOfSections - 1];
}

Solution 3:

In swift 3

let lastRowIndex = tableView.numberOfRows(inSection: tableView.numberOfSections-1)

if (indexPath.row == lastRowIndex - 1) {
     print("last row selected")
}