如何获得 UICollectionViewCell 的正确信息?

UITableView具有方法 rectForRowAtIndexPath:,但是这在 UICollectionView 中不存在。我正在寻找一个不错的干净的方法来抓取一个单元的边界矩形,也许我可以添加到 UICollectionView作为一个类别。

40683 次浏览

怎么样

-(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

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

目标 C

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

斯威夫特

let attributes = collectionView.layoutAttributesForItem(at: indexPath)

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

你可以迅速地做:

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


//if you only need for visible cells
let rect = cellForItemAtIndexPath(indexPath)?.frame

只需要两行代码就可以得到完美的帧:

目标-C

UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];


CGRect cellFrameInSuperview = [collectionView convertRect:theAttributes.frame toView:[collectionView superview]];

迅捷4.2

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

在雨燕3

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