0

I've used this code for to get an UIButton from inside my UITableViewCell but it didn't work. So I've debugged it like half an hour to know what superview it in is.

UIButton *button = (UIButton *)sender;
UITableViewCell* cell = (UITableViewCell*)button.superview.superview.superview;
UITableView* tableView = (UITableView*) cell.superview.superview;
NSIndexPath* indexPath = [tableView indexPathForCell:cell];

The question for me is now: How can I know in the future in what hierarchy it is for a UITableView or others? Isn't there a list where I can see how much superviews I need to go without testing it 100 times and set BreakPoints to see what class it refers to?

Regards

  • Add a breakpoint in your code... when it pauses, try with `po [UIWindow recursiveDescription];` You can replace UIWindow with almost any valid UIView. I'd be cautious with this method though, as @architectpianist rightly mentions it's problems. – dezinezync Jul 05 '14 at 18:15
  • I humbly suggest my solution in the marked duplicate as the best way to solve this. – jrturton Jul 05 '14 at 18:17

2 Answers2

1

You may just end up going with the superview hierarchy route, but know this is not a good idea because Apple could change their table view hierarchy any time. There are much better ways to get the index path for a table view cell given a button inside one of the cells.

  1. If all the buttons are in one section of the table view, simply set each button's tag to the cell's index path row. Then you can recreate the index path knowing which row the button is in.

  2. You can always subclass UITableViewCell and implement the action method for the button inside the subclass. The subclass might call a delegate method to whichever object wanted to know about the button tap.

So hopefully this gives you an idea of the alternatives to what you were doing before. As you said, it's time-consuming to figure out the superview hierarchy and it could change at any time.

architectpianist
  • 2,562
  • 1
  • 19
  • 27
0

If you want to check multiple superview hierarchy then check like that below:-

UIView * view=(UIView*)sender;

while ((view= [view superview])) {
    if(viewisKindOfClass:[UITableView class]) {
        //your code
        return;
    }
}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56