Is there any way to know which collection view cel

2019-07-19 05:47发布

问题:

I have a CGPoint and I would like to know which cell from my collection view currently contains that point. Is there any simple way to do this or do I have to write my own method?

回答1:

I haven't used UICollectionViews much, but there's a method that seems perfect:

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

The point you pass to the method has to be within the coordinate system of the collection view. You can do:

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

to get the correct point, if the point you got isn't from the collection view originally.



回答2:

//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)
         }
}