Getting the screen location of a cell from a UICollectionView

前端 未结 6 1432
野性不改
野性不改 2021-01-30 10:20

This isn\'t so much a question as an explanation of how to solve this problem.

The first thing to realize is that the UICollectionView does inherit from a <

6条回答
  •  盖世英雄少女心
    2021-01-30 10:54

    @Alivin solution using layoutAttributesForItemAtIndexPath works but only for the presented/current scroll view that the user sees.

    Meaning, if you select the first presented visible cells you will get the actual frame, but if you scroll, the frame will have a deviation and you won't get the coordinates you need.

    This is why you need to use convertPoint:toView :

    let realCenter = collectionView.convertPoint(cell.center, toView: collectionView.superview)
    

    Basically this method takes a point (cell.center) in one view and convert that point to another view (collectionView.superview) coordinate system which is exactly what we need.

    Thus, realCenter will always contain the coordinates to the actual selected cell.

提交回复
热议问题