Search code examples
iosobjective-ccell

How do I reach a sender's parent view?


I have a button inside a custom cell. When tapped the button presents a view via a modal segue.

So, here's my question, in the prepareForSegue:sender: I want to pull the indexPath of the cell which contains that button(sender) that I pushed. How do I get that cell's indexPath?

I thought I could do something like:

UITableViewCell * cell = sender.parent 

Obviously it doesn't work that way.

Please help me out.

UPDATE Thanks to @rmaddy I've tried [[sender superview] superview] and got to the cell in which the button was held and to it's indexPath. Thanks for your answers guys!


Solution

  • Assuming sender is a UIVIew of some sort (such as a UIButton), then:

    UIView *parentView = [(UIView *)sender superview];
    

    If you are positive that the button's superview is the table cell then you can do:

    UITableViewCell *cell = (UITableViewCell *)[(UIView *)sender superview];
    

    Once you have the cell, use the table view's indexPathForCell: method.

    Keep in mind that if you actually added the button to the cell's contentView or some other subview of the cell, then getting the cell from the button is a bit trickier.