Joseph Toronto
Joseph Toronto

Reputation: 1892

Get reference to UITableViewCell from IBAction?

I have a tableview that uses a UIButton in a custom UITableViewCell that triggers an IBAction in my view controller. In IOS7 I was able to reference the specific cell the action was triggered from by doing this UITableViewCell *clickedCell = (UITableViewCell *)[[[sender superview] superview]superview].

This worked fine in iOS7, however it seems in iOS8 it requires one of the superviews to be removed to return the cell, otherwise it returns nil. So I'm doing it this way now, and it works, but I was wondering if there was a cleaner way to implement this. I just don't like the way this looks.

 UITableViewCell *clickedCell;

if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
     clickedCell = (UITableViewCell *)[[[sender superview] superview]superview];
}
else{
     clickedCell = (UITableViewCell *)[[sender superview]superview];
}

Upvotes: 0

Views: 115

Answers (1)

dfmuir
dfmuir

Reputation: 2088

You could subclass the UIButton to MYButton and add a property like this:

@property (nonatomic, weak) UITableViewCell *parentCell;

Then, when you set up the UIButton from the cell set parentCell = self

From there you could simply access the cell by:

MYButton *button = (MYButton *)sender;
clickedCell = sender.parentCell.

Make sure to use a weak property so you do not create a retain cycle.

Upvotes: 2

Related Questions