How to get the rect of a UICollectionViewCell?

后端 未结 5 1814
北海茫月
北海茫月 2020-12-23 11:05

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

相关标签:
5条回答
  • 2020-12-23 11:38

    in swift 3

     let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath)
     let cellFrameInSuperview:CGRect!  = collectionView.convert(theAttributes.frame, to: collectionView.superview)
    
    0 讨论(0)
  • 2020-12-23 11:40

    in swift you can just do:

    //for any cell in collectionView
    let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame
    
    //if you only need for visible cells
    let rect = cellForItemAtIndexPath(indexPath)?.frame
    
    0 讨论(0)
  • 2020-12-23 11:43

    How about

    -(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath {
    
        UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath];
    
        if (!cell) {
            return CGRectZero;
        }
    
        return cell.frame;
    
    }
    

    as a category on 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)
  • 2020-12-23 11:44

    Only two lines of code is required to get perfect frame :

    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)
    
    0 讨论(0)
  • 2020-12-23 11:56

    The best way I've found to do this is the following:

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

    0 讨论(0)
提交回复
热议问题