2

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:.

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143

2 Answers2

4

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
idhong
  • 41
  • 3
  • Your answer appears to be all code. Add some words describing what the problem was and your solution. – Matt Jul 28 '17 at 01:52
  • @idhong - Looks like you were having trouble adding code to your post and having it correctly formatted. To properly format code, you need to add four spaces before each line. You can also paste in code, select it all, and hit CTRL-K in the editor to automatically do that for you – Rob Jul 28 '17 at 01:59
1

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.

kaushal
  • 1,553
  • 18
  • 25