How to get UICollectionViewCell address?

UITableView has a rectForRowAtIndexPath: method, but this does not exist in UICollectionView. I'm looking for a nice clean way to grab a rectangle with a cell, maybe one that I could add as a category on a UICollectionView .

+57
ios uitableview ios6 uicollectionview
Sep 20 '12 at 1:14
source share
5 answers

The best way I found for this is as follows:

Objective-c

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

swift

 let attributes = collectionView.layoutAttributesForItem(at: indexPath) 

Then you can access the location via attributes.frame or attributes.center

+122
Sep 24
source share

It takes only two lines of code to get the 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) 
+33
May 11 '15 at 9:23
source share

in fast 3

  let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath) let cellFrameInSuperview:CGRect! = collectionView.convert(theAttributes.frame, to: collectionView.superview) 
+15
Feb 24 '17 at 10:47
source share

in fast mode:

 //for any cell in collectionView let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame //if you only need for visible cells let rect = cellForItemAtIndexPath(indexPath)?.frame 
+7
May 7, '15 at 17:43
source share

What about

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

How is the category on a 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 
-one
Sep 20 '12 at 6:15
source share



All Articles