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 UICollectionView
s 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)
}
}