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

梦想与她 提交于 2019-12-24 01:51:35

问题


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


来源:https://stackoverflow.com/questions/13404533/is-there-any-way-to-know-which-collection-view-cell-is-at-a-specific-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!