如何获得UICollectionViewCell的矩形?

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

我发现要做到这一点的最佳方式如下:

 UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath]; 

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

只有两行代码才能获得完美的帧:

 UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath]; CGRect cellFrameInSuperview = [collectionView convertRect:theAttributes.frame toView:[collectionView superview]]; 

在迅速3

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

在迅速,你可以做:

 //for any cell in collectionView let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame //if you only need for visible cells let rect = cellForItemAtIndexPath(indexPath)?.frame 

怎么样

 -(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath]; if (!cell) { return CGRectZero; } return cell.frame; } 

作为UICollectionView的类别?

 #import <UIKit/UIKit.h> @interface UICollectionView (CellFrame) -(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath; @end #import "UICollectionView+CellFrame.h" @implementation UICollectionView (CellFrame) -(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath]; if (!cell) { return CGRectZero; } return cell.frame; } @end