2

我有一个 CGPoint,我想知道我的收藏视图中的哪个单元格当前包含该点。有什么简单的方法可以做到这一点,还是我必须编写自己的方法?

4

2 回答 2

13

s用UICollectionView的不多,但是有一种方法看起来很完美:

- (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point;

您传递给该方法的点必须在集合视图的坐标系内。你可以做:

CGPoint convertedPoint = [collectionView convertPoint:point fromView:viewThatYouGotThePointFrom];

如果您获得的点最初不是来自集合视图,则获得正确的点。

于 2012-11-15T19:24:18.740 回答
4
//due to the point passed in possibly not containing a cell IndexPath is an optional

func indexPathForCellAtPoint(_ point : CGPoint) -> IndexPath? {
                   return collectionView?.indexPathForItem(at: self.view.convert(point, to: collectionView!))
}


override func scrollViewDidScroll(_ scrollView: UIScrollView) {
   let topLeftCell = CGPoint(x: 1, y: 60)
       if let indexPath = indexPathForCellAtPoint(topLeftCell) {
                    print(indexPath.section,indexPath.row)
         }
}
于 2018-02-05T10:04:53.303 回答