iOS自定义TableView的Cell点击事件

公司同事遇到了一个问题向笔者求助:在UITableView的代理函数didSelectRowAtIndexPath中发现indexPath并不是实际点击的row,难道是iOS系统出错?经过不断调试并没查出实际原因,后来笔者只好仿造一个Cell的点击事件。

思路很简单,就是给TableView添加一个UITapGestureRecognizer,然后在action中判断是哪个Cell。

第一步:添加触摸机制

// 用此方式替代TableView代理的didSelectRowAtIndexPath函数
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTableViewClick:)];
[self.myTableView addGestureRecognizer:tapGesture];

第二步:判断哪个cell

#pragma mark - 点击事件
- (void)myTableViewClick:(UIGestureRecognizer *)gestureRecognizer {
    
    
    CGPoint point = [gestureRecognizer locationInView:self.myTableView];
    NSIndexPath *indexpath = [self.myTableView indexPathForRowAtPoint:point];
    if ([self respondsToSelector:@selector(m_tableView:didSelectRowAtIndexPath:)]) {
    
    
        [self m_tableView:self.myTableView didSelectRowAtIndexPath:indexpath];
    }
}

第三步:实现Cell点击

-(void)m_tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
        // 逻辑处理
}

PS:UITableView的原生代理点击事件(tableView:didSelectRowAtIndexPath:)就不需要实现了,自己定义一个第三步的函数就好。

猜你喜欢

转载自blog.csdn.net/xiao19911130/article/details/108102930