如何获取UICollectionViewCell的矩形框(rect)?

75

UITableViewrectForRowAtIndexPath:方法,但在UICollectionView中不存在。我正在寻找一种简洁的方式来获取单元格的边界矩形,也许可以将其作为UICollectionView的类别添加。

(注意:已保留HTML标记)
5个回答

154

我发现最好的方法如下:

Objective-C

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

Swift

let attributes = collectionView.layoutAttributesForItem(at: indexPath)

然后你可以通过 attributes.frameattributes.center访问位置。


17
这将给出单元格相对于父视图的绝对位置。CGRect cellFrameInSuperview = [self.collectionView convertRect:attributes.frame toView:[self.collectionView superview]]; - Maverick

54

只需两行代码即可获得完美的框架:

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)

1
这正是我所需要的,它可以在滚动时提供更新的框架。 - Marc

18

在Swift 3中

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

9
在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

-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

这个代码有效,但给出的单元格框架是相对于其自身视图层次结构的(这意味着每个单元格的原点都是{0,0})。我需要知道在表视图中矩形的位置。 - akaru
2
cellForItemAtIndexPath方法只返回可见单元格的值。如果indexPath处的单元格不在屏幕上,则返回nil。 - Ashley Mills
对于可见单元格运行良好,OP没有指定是否为可见单元格。 - phatmann
1
仅适用于可见单元格! - skywinder
这是用于带有父级的单元格的“rect”,而不是集合视图,您将看到x,y = 0。 - famfamfam
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接