ios 如何获取 UICollectionViewCell 的矩形?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12504924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the rect of a UICollectionViewCell?
提问by akaru
UITableView
has the method rectForRowAtIndexPath:
, but this does not exist in UICollectionView. I'm looking for a nice clean way to grab a cell's bounding rectangle, perhaps one that I could add as a category on UICollectionView
.
UITableView
有方法rectForRowAtIndexPath:
,但在 UICollectionView 中不存在。我正在寻找一种非常干净的方式来抓取单元格的边界矩形,也许我可以将其添加为UICollectionView
.
回答by simon
The best way I've found to do this is the following:
我发现这样做的最佳方法如下:
Objective-C
目标-C
UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
Swift
迅速
let attributes = collectionView.layoutAttributesForItem(at: indexPath)
Then you can access the location through either attributes.frame
or attributes.center
然后,您可以通过访问该位置要么attributes.frame
或attributes.center
回答by Shaik Riyaz
Only two lines of code is required to get perfect frame :
只需两行代码即可获得完美的框架:
Objective-C
目标-C
UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];
CGRect cellFrameInSuperview = [collectionView convertRect:theAttributes.frame toView:[collectionView superview]];
Swift 4.2
斯威夫特 4.2
let theAttributes = collectionView.layoutAttributesForItem(at: indexPath)
let cellFrameInSuperview = collectionView.convert(theAttributes.frame, to: collectionView.superview)
回答by Spydy
in swift 3
在迅速 3
let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath)
let cellFrameInSuperview:CGRect! = collectionView.convert(theAttributes.frame, to: collectionView.superview)
回答by Victor --------
in swift you can just do:
在 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
回答by TimD
How about
怎么样
-(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath];
if (!cell) {
return CGRectZero;
}
return cell.frame;
}
as a category on UICollectionView
?
作为一个类别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