cell上的button获取indexPath信息

ios开发中,在cell上添加按钮是很常见的做法。

当点击button的时候,如何获取到当前点击cell的indexPath呢?

从tabelView的代理方法里面我们可以找到几个与NSIndexPath相关的Api

1、根据所在的row位置获取NSIndexPath

- (nullableNSIndexPath*)indexPathForRowAtPoint:(CGPoint)point;                        

2、根据cell获取NSIndexPath

- (nullableNSIndexPath*)indexPathForCell:(UITableViewCell*)cell;   

每一个点击事件生成都会有一个UIEvent的生成,所以可以通过UIEvent来获取按钮的点击事件

首页先给按钮添加点击事件

[button addTarget:self action:@selector(clickBtn:event:) forControlEvents:UIControlEventTouchUpInside];

实现点击事件

#pragma mark--点击cell上面的按钮事件

-(void)clickBtn:(UIButton*)button event:(UIEvent*)event{

    //获取所有的event事件

    NSSet*touches =[event  allTouches];

    //获取点击event事件

    UITouch*touch =[touches  anyObject];

    //获取所点击的位置信息

    CGPoint currentTouchPosition = [touch locationInView:self.tableView];

    //将位置转换为indexPath信息

    NSIndexPath*indexPath=    [self.tableView indexPathForRowAtPoint:currentTouchPosition];


    //调用cell的didSelectRowAtIndexPath方法

    if(indexPath !=nil) {

        [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

    }

}

你可能感兴趣的:(cell上的button获取indexPath信息)