问题
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.
回答1:
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.
回答2:
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];
回答3:
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];
来源:https://stackoverflow.com/questions/19100557/getting-uitableviewcell-from-its-superview-ios-7-issue