·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 长按Cell进行选择

长按Cell进行选择

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

新手,勿喷~

----------------------------------------------------------------------------------------------------------------------------------------------------------------

最近这几天做了一个长按Cell删除的功能。

添加了一个UILongPRessGestureRecognizer长按手势,在手势的方法里,直接写

if (sender.state == UIGestureRecognizerStateBegan) {

}
然而再这个时候遇到了问题,我用下边的办法找到了cell的indexPath

 CGPoint point = [sender locationInView:self.tableView];
 NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];

问题来了,平时我都是实例化一个cell,然后用indexPath.section和indexPath.row来确定不同位置的cell,给其加载数据。但是现在我只知道indexPath,怎么才能找到它所对应的cell。额,难倒了我这个初学者,第一次遇到这种问题。后来看到了- (NSArray *)visibleCells;  这个方法是用来获取屏幕上显示的所有cell.

So happy,通过indexPath.row获取cell,终于搞定。

NSArray *cells = [self.tableView visibleCells];
MapTableViewCell *cell = cells[indexPath.row];

前几个cell没有任何问题。然而当表示图开始滚动以后,再选择cell,就遭遇了各种崩溃。纠结了很久,发现崩溃的原因很简单,数组越界。因为indexPath是递增的,而cell的个数是固定的,自然而然,indexPath.row大于cell.count了。解决办法很easy,cell.tag = indexPath.row; 找到症结,解决麻烦!

 if (sender.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [sender locationInView:self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
        if(indexPath == nil) return ;
        
        NSArray *cells = [self.tableView visibleCells];
        NSInteger tag = ((UITableViewCell *)[cells firstObject]).tag;
        UITableViewCell *cell = cells[indexPath.row - tag];
    }
最后的结果就变成了这个样子,我拿到了长按手势点击的cell。