Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the indexPath of UIButton in a customized tableViewCell?

Tags:

iphone

I created a tableViewCell the include an image, two text labels and a uibutton. The button is allocated to an action method (e.g. viewButtonPused:sender).

I'm used to handle row selection with tableView:didSelectRowAtIndexPath: so I could tell which row was selected. But with the uibutton and its action method .... How can I tell?

Thanks in advance.

like image 376
Tzur Gazit Avatar asked Nov 28 '22 19:11

Tzur Gazit


1 Answers

If the button's target is the UIViewController/UITableViewController or any other object that maintains a reference to the UITableView instance, this will do nicely:

- (void)viewButtonPushed:(id)sender {
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = button.superview; // adjust according to your UITableViewCell-subclass' view hierarchy
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    // use your NSIndexPath here
}

Using this approach will let you avoid extra instance variables and will work fine in case you have multiple sections. You need to have a way to access the UITableView instance though.

Edit: as someone pointed out in the comments below, this approach broke in iOS 7. If you're still interested in using this approach over tags, be sure to find the UITableViewCell instance correctly, i.e. by looping through the superviews until you find one.

like image 139
Alex Repty Avatar answered Jun 06 '23 21:06

Alex Repty