UITextField subview of UITableViewCell, get indexPath of cell
Call [UIView superview]
on the field to get the cell that it's in, then call [UITableView indexPathForCell:]
on the cell to get the index path.
UPDATE: on iOS 7 you need to call superview on that view too (extra layer of views); here's a category on UITableView that should work independent of iOS version:
@interface UITableView (MyCoolExtension)
- (NSIndexPath *)indexPathForCellContainingView:(UIView *)view;
@end
@implementation UITableView (MyCoolExtension)
- (NSIndexPath *)indexPathForCellContainingView:(UIView *)view {
while (view != nil) {
if ([view isKindOfClass:[UITableViewCell class]]) {
return [self indexPathForCell:(UITableViewCell *)view];
} else {
view = [view superview];
}
}
return nil;
}
@end
Instead of recursively trying to find the superview, there's a simpler solution:
Swift
func indexPathForCellContainingView(view: UIView, inTableView tableView:UITableView) -> NSIndexPath? {
let viewCenterRelativeToTableview = tableView.convertPoint(CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds)), fromView:view)
return tableView.indexPathForRowAtPoint(viewCenterRelativeToTableview)
}
Objective-C
- (NSIndexPath *)indexPathForCellContainingView:(UIView *)view inTableView:(UITableView *)tableView {
CGPoint viewCenterRelativeToTableview = [tableView convertPoint:CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds)) fromView:view];
NSIndexPath *cellIndexPath = [tableView indexPathForRowAtPoint:viewCenterRelativeToTableview];
return cellIndexPath
}
I made this into a Gist for the Swift hearted