How do I get rect for UICollectionView

1.6k Views Asked by At

I want to locate the frame of section header in UICollectionView. I have a similar situation for UITableView, and for that, I was able to get its rect by doing:

 CGRect rect = [self.tableView rectForHeaderInSection:section];

Is there a way to get the same result in UICollectionView? Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

Sorry, guys. It was actually easy.

 NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:section];
 UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
 CGRect rect = [attributes frame];
0
On

Swift version of @tsuyoski's answer:

let section = 0 // or whatever section you're interested in

let indexPath = IndexPath(item: 0, section: section)
let attributes = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath)
guard let rect = attributes?.frame else { return }