iOS关于提高获取NSIndexPath准确性的方法

2018-12-19  本文已影响34人  流年划过颜夕

在编写collectionView过程中,有时需要根据其对应的cell找到与之对应的indexpath进行数据处理,
常用的方法如下:

也就是:
NSIndexPath *indexpath =[self.collectionView indexPathForCell:cell];

但是有时会出现很奇怪的事情,就是collectionView存在,返回的cell也是存在的,但是获取到的indexpath却有时为空。

文档上对Return Value的解释如下:
The index path of the cell or nil if the specified cell is not in the collection view.

也就是说只要cell是不可见的时候就会返回nil,个人感觉“不可见”是指系统认为的不可见,实际上只要能点击触发事件且返回了cell,就侧面反应了cell是存在的。
所以说:

这个方法在某种特定的使用场景上存在隐患。

那有什么用一种办法能够提高返回indexpath的准确性呢?

答案肯定是有的,以下的方法就相对实用得多:

文档上对Return Value的解释如下:
An index path representing the row and section associated with point, or nil if the point is out of the bounds of any row.

综上
如果做点击等触控事件去通过cell获取indexPath:
那采用
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];

准确性能大大提升,能在cell范围内点击中就会返回indexPath。

上一篇 下一篇

猜你喜欢

热点阅读