5

I have a UITableView with custom cells. Within each UITableViewCell, there is a UIButton. I'm attempting to find out which cell the button is located in when it is tapped. To do this I've done this:

- (IBAction)likeTap:(id)sender {


UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];
UITableView* table = (UITableView *)[buttonCell superview];
NSIndexPath *pathOfTheCell = [table indexPathForCell:buttonCell];
NSInteger rowOfTheCell = [pathOfTheCell row];
NSLog(@"rowofthecell %d", rowOfTheCell);

I thought this would work fine, but when indexPathForCell is called, an exception is thrown.

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCell indexPathForCell:]: unrecognized selector sent to instance 0x756d650'

Any ideas about what I've done wrong? Thanks!

4 Answers4

6

This is your problem:

(UITableViewCell *)[senderButton superview]

It should be:

(UITableViewCell *)[[senderButton superview] superview]

Because the superview of the button is not the cell, is the contentView which subview of the cell.

Avi Tsadok
  • 1,843
  • 13
  • 19
2

Why you dont set tag for each button in your cellForRowAtIndexPAth method:

button.tag = indexPath.row;

and then in your method you have:

- (IBAction)likeTap:(id)sender {
    NSLog(@"rowofthecell %d", button.tag);
}
edzio27
  • 4,126
  • 7
  • 33
  • 48
2

I use custom UITableViewCell and i have a crash too on ios7

On ios 6, it's work like a charm

UITableViewCell *cell=(UITableViewCell*)[[sender superview] superview];
UITableView *table=(UITableView*)[cell superview];
NSIndexPath *path=[[sender superview] indexPathForCell:cell];

on ios7, this code above crash,

This code works on ios7 but i don't understand why...

UITableViewCell *cell = (UITableViewCell*)[[sender superview] superview];
UITableView *table = [[(UITableView*)[cell superview] superview] superview];
NSIndexPath *path=[[sender superview] indexPathForCell:cell];

So i use edzio27 answer. I set a tag on my button.

MrP
  • 1,408
  • 18
  • 23
1

Either you can set tag for each button as suggested by edzio27 or you can try using introspection as shown below :

- (IBAction)likeTap:(UIButton *)sender {

    UIButton *senderButton = (UIButton *)sender;

    if ([senderButton.superView isKindOfClass:[UITableViewCell class]]) {
        UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];

        if ([buttonCell.superView isKindOfClass:[UITablewView class]]) {
            UITableView* table = (UITableView *)[buttonCell superview];

            NSIndexPath *pathOfTheCell = [table indexPathForCell:buttonCell];
            NSInteger rowOfTheCell = [pathOfTheCell row];
            NSLog(@"rowofthecell %d", rowOfTheCell);
        }
    }           
}
Geek
  • 8,280
  • 17
  • 73
  • 137