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?
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.
//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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With