长按Cell进行选择

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

新手,勿喷~

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

最近这几天做了一个长按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。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航