【发布时间】:2012-09-12 08:45:20
【问题描述】:
UITableView 有 rectForRowAtIndexPath: 方法,但在 UICollectionView 中不存在此方法。我正在寻找一种干净的方法来获取单元格的边界矩形,也许我可以将其添加为UICollectionView 上的类别。
【问题讨论】:
标签: ios uitableview ios6 uicollectionview
UITableView 有 rectForRowAtIndexPath: 方法,但在 UICollectionView 中不存在此方法。我正在寻找一种干净的方法来获取单元格的边界矩形,也许我可以将其添加为UICollectionView 上的类别。
【问题讨论】:
标签: ios uitableview ios6 uicollectionview
我发现最好的方法如下:
Objective-C
UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
斯威夫特
let attributes = collectionView.layoutAttributesForItem(at: indexPath)
然后您可以通过attributes.frame 或attributes.center 访问该位置
【讨论】:
CGRect cellFrameInSuperview = [self.collectionView convertRect:attributes.frame toView:[self.collectionView superview]];
只需要两行代码即可获得完美的框架:
Objective-C
UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];
CGRect cellFrameInSuperview = [collectionView convertRect:theAttributes.frame toView:[collectionView superview]];
Swift 4.2
let theAttributes = collectionView.layoutAttributesForItem(at: indexPath)
let cellFrameInSuperview = collectionView.convert(theAttributes.frame, to: collectionView.superview)
【讨论】:
在 Swift 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
【讨论】:
UIView的convertRect:toView:方法将rect相对于collection view进行转换。