UITableView
有方法rectForRowAtIndexPath:
,但这在UICollectionView中不存在。我正在寻找一种干净的方式来获取单元格的边界矩形,也许我可以将其添加为UICollectionView
.
问问题
39142 次
5 回答
149
我发现这样做的最佳方法如下:
Objective-C
UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
迅速
let attributes = collectionView.layoutAttributesForItem(at: indexPath)
然后您可以通过attributes.frame
或访问该位置attributes.center
于 2012-09-24T04:54:05.420 回答
53
只需两行代码即可获得完美的框架:
Objective-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)
于 2015-05-11T09:23:32.580 回答
18
在迅速 3
let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath)
let cellFrameInSuperview:CGRect! = collectionView.convert(theAttributes.frame, to: collectionView.superview)
于 2017-02-24T10:47:11.340 回答
9
迅速你可以这样做:
//for any cell in collectionView
let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame
//if you only need for visible cells
let rect = cellForItemAtIndexPath(indexPath)?.frame
于 2015-05-07T17:43:57.750 回答
-2
怎么样
-(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
于 2012-09-20T06:15:35.253 回答