UITextField subview of UITableViewCell, get indexPath of cell

前端 未结 5 1266
余生分开走
余生分开走 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:54

    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

提交回复
热议问题