I have a UIButton
in a custom UITableViewCell
. This button triggers an event when clicked.
[myButton addTarget:self action:@selector(b
As you rightly say, the button is "in" the cell - in the sense that it is a subview, at some depth, of some cell. So simply walk up the view hierarchy until you reach the cell:
- (void) buttonClicked:(id)sender {
UIView* v = sender;
while (![v isKindOfClass:[UITableViewCell class]])
v = v.superview;
// now v is the cell
}
You can set tag to button when you are adding the buttons in table view cell. It will be better if you use same indexPath of able view cell. Then from [sender tag] you able to get the indexPath value.
- (void) buttonClicked:(id)sender
{
UIButton *b = (UIButton*)sender;
UITableViewCell *tableViewCell =(UITableViewCell*) [b superview];
//if you added the UIButton as a subview of UITableViewCell contendView, use this
UITableViewCell *tableViewCell =(UITableViewCell*) [[b superview] superview];
}
UITableViewCell *cell = (UITableViewCell*)[[b superview] superview];
If you added the button on cell as subview then superview of button will be contentView and superview of contentView will UITableViewCell
I'd suggest you not just to put a button into a UITableViewCell. What you should better to is to subclass UITableViewCell and make UITableViewButtonCell that will cal a delegate callback like this: - (void) tableViewButtonCellDidButtonTap:(UITableViewCell*) buttonCell
This will be more SOLID solution.
The case with
UIButton *b = (UIButton*)sender;
will only work if your button lies DIRECTLY insade the UITableviewCell that can possibly be not a case.
UITableViewCell *tableViewCell =(UITableViewCell*) [b superview];