有没有办法知道哪个集合视图单元格在特定点?

时间:2012-11-15 19:16:29

标签: objective-c ios uicollectionview cgpoint uicollectionviewcell

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

2 个答案:

答案 0 :(得分:12)

我没有使用UICollectionView,但有一种方法似乎很完美:

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

传递给方法的点必须位于集合视图的坐标系内。你可以这样做:

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

获取正确的点,如果你得到的点不是最初的集合视图。

答案 1 :(得分:1)

//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)
         }
}
相关问题