How to get indexPath in a tableview from a button action in a cell?

Sylvain Bessot picture Sylvain Bessot · Sep 17, 2011 · Viewed 10k times · Source

I have a tableview with two actions in it, for the first on i use the delegate didSelectRowAtIndexPath, for the second one i would like to use an action on a button on my cell to do something else. My problem is that i don't succeed to get the indexpath ? What is the best practice to do that.

Answer

EmptyStack picture EmptyStack · Sep 17, 2011

If you have added the button to the cell as,

[cell.contentView addSubview:button];

then, you can get the index path as,

- (void)onButtonTapped:(UIButton *)button {

    UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];
    // Go ahead
}