UITextField subview of UITableViewCell, get indexPath of cell

前端 未结 5 1255
余生分开走
余生分开走 2020-11-30 08:30

I have added a UITextField as a subview of a UITableViewCell. Then I have added a target and selector so that I can know

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 08:52

    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
    

提交回复
热议问题