0

I have a (horizontal) collection-view, and I change its size via auto layout constraints. However, when the collection-view's size changes, the cell remains the same static size.

To demonstrate, here's the collection-view in the view debugger (I've labeled both the collectionview and one of its cells):

enter image description here

As you can see, the cell remains the original size and is now actually taller than its encasing collection-view.

So how can I constrain the cell to always fit within its collection-view?

vikzilla
  • 3,998
  • 6
  • 36
  • 57

2 Answers2

0

If you want to resize your view you can use the following to reset the item size on rotation, this would go inside your view controller subclass.

This should be fairly efficent as it is only called when the size of the visible view controller changes.

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator;
{
  [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

  [coordinator animateAlongsideTransition:({
    ^(id<UIViewControllerTransitionCoordinatorContext> context) {

      UICollectionViewFlowLayout *layout = (id)self.collectionView.collectionViewLayout; {

        CGFloat height = CGRectGetHeight(self.collectionView.bounds);

        layout.itemSize = (CGSize) {
          .width  = height,
          .height = height
        };

      }

      [layout invalidateLayout];

    };
  }) completion:nil];

}

You should also check out these answers for some more solutions.

Community
  • 1
  • 1
Oliver Atkinson
  • 7,970
  • 32
  • 43
  • I solved this through setting the cell's size to that of the collection-view height in sizeForItemAtIndexPath. Appreciate your help – vikzilla Feb 14 '16 at 21:50
0

I solved this through setting the item's height and width equal to the collection-view's height. I do this in sizeForItemAtIndexPath:

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(collectionView.frame.size.height, collectionView.frame.size.height);
}

Because in my case the cell's need to be perfect squares, setting the cell's height and width to the height of the collection-view works perfectly.

Not that your class must implement the UICollectionViewDelegateFlowLayout protocol for this method to be exposed.

vikzilla
  • 3,998
  • 6
  • 36
  • 57