当调用indexPathForCell时崩溃

5

我有一个带有自定义单元格的UITableView。在每个UITableViewCell中,都有一个UIButton。当按钮被点击时,我尝试找出它所在的单元格。为了做到这一点,我已经进行了以下操作:

- (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);

我以为这样做没问题,但当调用indexPathForCell时,会抛出异常。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCell indexPathForCell:]: unrecognized selector sent to instance 0x756d650'

有什么想法我做错了什么吗?谢谢!
4个回答

6
这是您的问题:
(UITableViewCell *)[senderButton superview]

应该是:

(UITableViewCell *)[[senderButton superview] superview]

由于按钮的父视图不是单元格,而是单元格的子视图contentView。

注意:这将在iOS7上运行,但在iOS6上不会! - Bishal Ghimire
你节省了我的时间,非常感谢。 - Vigor

2

为什么您在cellForRowAtIndexPAth方法中不为每个按钮设置标签:

button.tag = indexPath.row;

然后在你的方法中:

- (IBAction)likeTap:(id)sender {
    NSLog(@"rowofthecell %d", button.tag);
}

2

我使用自定义的UITableViewCell,在iOS7上也遇到了崩溃问题。

在iOS6上,它能够完美工作。

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

在iOS7上,以上代码会崩溃。
这段代码在iOS7上能够正常运行,但我不明白为什么...
UITableViewCell *cell = (UITableViewCell*)[[sender superview] superview];
UITableView *table = [[(UITableView*)[cell superview] superview] superview];
NSIndexPath *path=[[sender superview] indexPathForCell:cell];

所以我使用了edzio27的答案。我在我的按钮上设置了一个标签。

这是适用于iOS6和iOS7的解决方案:https://dev59.com/DHfZa4cB1Zd3GeqPNBSA#19651825 - Bishal Ghimire

1

你可以像edzio27建议的那样为每个按钮设置标签,或者尝试使用下面展示的内省

- (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);
        }
    }           
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接