Get UITableViewCell of UIButton?

前端 未结 2 1355
北海茫月
北海茫月 2021-01-28 17:56

I\'m trying to perform a segue using a UIButton, which is located within in a custom UITableViewCell class called GFHomeCell.

The

相关标签:
2条回答
  • 2021-01-28 18:28

    Well, one answer would be to just go up a level in the view hierarchy:

     - (void)commentButtonClick:(id)sender {
        GFHomeCell * cell = (GFHomeCell *) [(UIButton*)sender superview];
        if (cell && [cell Class] == [GFHomeCell class]) {
            //do whatever with cell.postID
            [self performSegueWithIdentifier:@"addCommentSegue" sender:sender];
         }
    }
    

    Oh, I forget... you may have to go up two levels to get past the contentView property:

       GFHomeCell * cell = (GFHomeCell *) [[(UIButton*)sender superview] superview];
    
    0 讨论(0)
  • 2021-01-28 18:34

    There are basically two common approaches to this situation. One is to search up through the button's superviews until you find the cell. You shouldn't rely on going up one or two levels, because the hierarchy has changed in the past, and may change again (you need to go up two levels in iOS 6, but 3 in iOS 7). You can do it like this,

    -(void)commentButtonClick:(UIButton *) sender {
        id superView = sender.superview;
        while (superView && ![superView isKindOfClass:[UITableViewCell class]]) {
            superView = [superView superview];
        }
        [self performSegueWithIdentifier:@"addCommentSegue" sender:superView];
    }
    

    The other way is to assign a tag to your button in cellForRowAtIndexPath: equal to the indexPath.row (if you only have one section), and then use sender.tag to get the indexPath of the cell that contained the tapped button.

    0 讨论(0)
提交回复
热议问题