Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to know which collection view cell is at a specific point?

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?

like image 931
Alex Avatar asked Dec 18 '25 07:12

Alex


2 Answers

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.

like image 176
MaxGabriel Avatar answered Dec 19 '25 22:12

MaxGabriel


//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)
         }
}
like image 45
RyanTCB Avatar answered Dec 19 '25 23:12

RyanTCB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!