如何获取UICollectionViewCell的矩形?

aka*_*aru 60 uitableview ios ios6 uicollectionview

UITableView有方法rectForRowAtIndexPath:,但这在UICollectionView中不存在.我正在寻找一个很好的干净方法来获取一个单元格的边界矩形,也许我可以添加一个类别UICollectionView.

sim*_*mon 127

我发现这样做的最好方法如下:

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过attributes.frame或访问该位置attributes.center

  • 这将给出与superview`CGRect cellFrameInSuperview = [self.collectionView convertRect:attributes.frame toView:[self.collectionView superview]]相关的单元格的绝对位置; (11认同)
  • 它仅适用于可见细胞 (5认同)

Sha*_*yaz 38

只需要两行代码即可获得完美的帧:

UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];

CGRect cellFrameInSuperview = [collectionView convertRect:theAttributes.frame toView:[collectionView superview]];
Run Code Online (Sandbox Code Playgroud)


Spy*_*ydy 15

在迅速3

 let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath)
 let cellFrameInSuperview:CGRect!  = collectionView.convert(theAttributes.frame, to: collectionView.superview)
Run Code Online (Sandbox Code Playgroud)


Vic*_*--- 9

在swift你可以做到:

//for any cell in collectionView
let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame

//if you only need for visible cells
let rect = cellForItemAtIndexPath(indexPath)?.frame
Run Code Online (Sandbox Code Playgroud)