3

I have few UI objects in the cell that have got gesture recognizer instance. I need to get cell where pressing object is located. I have the method below for getting it, but it just work before iOS 7:

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

for iOS 6 it return UITableViewCell

for iOS 7 it return UITableViewCellScrollView

I think the new cell has some additional views in iOS 7, that's why I grab UITableViewCellScrollView instead of UITableViewCell as before.

Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277

3 Answers3

10

The best way to get a table view cell from it's subview is to convert the subview's location to a location in the table view, then ask the table view for the index path of the cell at that point:

CGPoint subviewPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:subviewPosition];

Then, you can get the cell for that index path:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
Greg
  • 33,450
  • 15
  • 93
  • 100
3

As you can see, relying on the view hierarchy is not a good approach - Apple can break it at any time.

You should use a delegate protocol to connect your cell to the controller.

jsd
  • 7,673
  • 5
  • 27
  • 47
2
CGPoint subviewPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:subviewPosition];
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
NSIndexPath *path=[self.tableView indexPathForCell:cell];
dip
  • 129
  • 1
  • 4