4

I have the following layout in my dynamically-sized Storyboard:

enter image description here

However, when running the application (depending on the orientation), cells look like the following:

enter image description here

This is to be expected, because the previous cells had static heights and widths.

However, I'd like the cells to resize dynamically based on the device width (height can remain static for this purpose). The CollectionView itself resizes properly, because it's pinned to its superview, so how can cells be overridden with auto-layout constraints (vs. the static cell sizes dictated from the UICollectionView).

Jeffrey Berthiaume
  • 3,944
  • 3
  • 33
  • 43

2 Answers2

5

The simplest way seems to be over-riding the cell size via the delegate within my main View Controller:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    float cellWidth = (self.view.frame.size.width / 2) - 35;
    float cellHeight = cellWidth * 190.0f / 270.0f;
    return CGSizeMake(cellWidth, cellHeight);
}

I'd prefer to have as much display logic in the storyboard, but I suppose this is room for future improvement for Apple.

Jeffrey Berthiaume
  • 3,944
  • 3
  • 33
  • 43
1

The cell sizes aren't determined by auto layout, they're set by the itemSize property of the layout object. If you only have one cell type, then you only need one cell in the collection view in IB. When your collection view is loaded, you can set that size in code, based on the width of the collection view. I've done it like this,

-(void)viewWillLayoutSubviews {
    self.layout.itemSize = CGSizeMake(self.collectionView.bounds.size.width/2.5, 100);
}
rdelmar
  • 102,832
  • 11
  • 203
  • 218