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

4 回答 4

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.

于 2013-06-30T06:58:19.030 回答
2

我使用自定义 UITableViewCell 并且我在 ios7 上也崩溃了

在 ios 6 上,它的工作就像一个魅力

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 答案。我在我的按钮上设置了一个标签。

于 2013-09-24T11:58:39.840 回答
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);
}
于 2013-06-30T06:56:33.740 回答
1

您可以按照建议为每个按钮设置标签,edzio27也可以尝试使用introspection如下所示:

- (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);
        }
    }           
}
于 2013-06-30T07:06:13.947 回答