UITableView的indexPathForRowAtPoint属性

一、做项目时用到自定义单元格,且单元格中有按钮,项目功能扩展需要点击按钮在每一个单元格的后面增加一个视图,因此需要确定单元格的indexPath属性,然后根据每一个单元格的高度就可以确定每一个单元格的位置,因此就可以增加新的视图,该问题的关键是点击按钮后确定所在单元格的索引,这个时候就要用到一个非常重要的属性indexPathForRowAtPoint。

- (void)btnClicked:(id)sender event:(id)event
{
     NSSet *touches = [event allTouches];
     UITouch *touch = [touches anyObject];
     CGPoint currentTouchPosition = [touch locationInView:self.tableView];
     NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
}

又或者是添加手势的视图

-(void)clickCommentLabelAction:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint currentTouchPosition=[gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath=[self.tableView indexPathForRowAtPoint:currentTouchPosition];
    [self creatInputBox:indexPath]; 
}

二、单元格中有UITextField或者其他控件

首先想到的也是通过event事件来确定UITextField的所在位置,例如:

    @IBAction func textFieldDidChanged(_ sender: UITextField, forEvent event: UIEvent) {
    }
    @IBAction func textFieldDidBegin(_ sender: UITextField, forEvent event: UIEvent) {
    }
但是经过测试,事件发生时传递过来的event对象为0x00000000,即该对象是不能用的,因此不能通过该方法来确定所在单元格的索引。

解决方案:通过获取UITextField父视图的方法来获取它所在的单元格,然后通过单元格的坐标即可计算出所在单元格的索引

    if let currentCell = editingTextField?.superview.superview as? UITableViewCell {
       let indexPath = tableView.indexPathForRow(at: currentCell.center)
        //或者let indexPath = tableView.indexPath(for: currentCell)
    }











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值