How can I keep track of the index path of a button in a table view cell?

Jake picture Jake · May 19, 2010 · Viewed 15.3k times · Source

I have a table view where each cell has a button accessory view. The table is managed by a fetched results controller and is frequently reordered. I want to be able to press one of the buttons and obtain the index path of that button's table view cell. I've been trying to get this working for days by storing the row of the button in its tag, but when the table gets reordered, the row becomes incorrect and I keep failing at reordering the tags correctly. Any new ideas on how to keep track of the button's cell's index path?

Answer

wxactly picture wxactly · Jan 8, 2013

If you feel uncomfortable relying on button.superview, this method should be a little more robust than some of the other answers here:

UIButton *button = (UIButton *)sender;
CGRect buttonFrame = [button convertRect:button.bounds toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonFrame.origin];