Getting row of UITableView cell on button press

You should really be using this method instead:

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];

Swift version:

let buttonPosition = sender.convert(CGPoint(), to:tableView)
let indexPath = tableView.indexPathForRow(at:buttonPosition)

That will give you the indexPath based on the position of the button that was pressed. Then you’d just call cellForRowAtIndexPath if you need the cell or indexPath.row if you need the row number.

If you’re paranoid, you can check for if (indexPath) ... before using it just in case the indexPath isn’t found for that point on the table view.

All of the other answers are likely to break if Apple decides to change the view structure.

Leave a Comment