Rafał Sroka
Rafał Sroka

Reputation: 40030

Get the frame for a UICollectionView section

How to get the frame (CGRect value) of a whole section in a UICollectionView instance? I know that UITableView has a rectForSection: method. I am looking for a similar thing for UICollectionView.

I checked the documents for UICollectionViewFlowLayout but couldn't find anything that looks like rectForSection:.

Upvotes: 2

Views: 2662

Answers (2)

idhong
idhong

Reputation: 41

to collectionView add category

  @implementation UICollectionView (BMRect)

- (CGRect)bm_rectForSection:(NSInteger)section {
    NSInteger sectionNum = [self.dataSource collectionView:self numberOfItemsInSection:section];
    if (sectionNum <= 0) {
        return CGRectZero;
    } else {
        CGRect firstRect = [self bm_rectForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]];
        CGRect lastRect = [self bm_rectForRowAtIndexPath:[NSIndexPath indexPathForItem:sectionNum-1 inSection:section]];
        return CGRectMake(0, CGRectGetMinY(firstRect), CGRectGetWidth(self.frame), CGRectGetMaxY(lastRect) - CGRectGetMidY(firstRect));
    }
}

- (CGRect)bm_rectForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self layoutAttributesForItemAtIndexPath:indexPath].frame;
}

@end

Upvotes: 4

kaushal
kaushal

Reputation: 1573

Collection view section frame is depend on the collection view layout.It might be flow layout or custom layout. So you will not got the any predefined solution. But you can calculate it for your layout using

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

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];

I will suggest you to subclass UICollectionViewLayout and put you section frame calculation code inside it, so that you section frame will always be the updated one.

NOTE : These point will not give you superset of rect in case of section start point and end point not vertically aligned.To be honest there is no better way to get section frame.

Upvotes: 1

Related Questions