Iraklii
Iraklii

Reputation: 1315

UICollectionViewCell dynamic sizing for 4.4 and 5.5 inch

I have UICollectionView with cells in the storyboard. The size of each cell is set to 145x145.

They look good on the iPhone 4 - 5s, but the size doesn't increase proportionally on the iPhone 6 and 6+. Rather than manually setting a different cell size for each device, how can I do it dynamically?

See examples here: iPhone 5S: http://prntscr.com/55vy7q, iPhone 6: http://prntscr.com/55vyy2

Upvotes: 15

Views: 4791

Answers (1)

user4151918
user4151918

Reputation:

If you want your cells to adjust their width, you'll need to calculate the flow layout's itemSize based on the view width.

  • If all your cells will be the same size, you can set the flow layout's itemSize property:

    #define kCellsPerRow 2
    
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
    CGFloat availableWidthForCells = CGRectGetWidth(self.collectionView.frame) - flowLayout.sectionInset.left - flowLayout.sectionInset.right - flowLayout.minimumInteritemSpacing * (kCellsPerRow - 1);
    CGFloat cellWidth = availableWidthForCells / kCellsPerRow;
    flowLayout.itemSize = CGSizeMake(cellWidth, flowLayout.itemSize.height);
    

    If you want to dynamically vary the number of cells per row, I've provided those details in a separate answer.

  • If you need to calculate per-cell sizes, you can do it in the collectionView:layout:sizeForItemAtIndexPath: delegate.

Recalculate the itemSize when the device orientation changes and update the layout:

  • Redraw layout without animation:

    [self.collectionView.collectionViewLayout invalidateLayout]

  • Animate layout changes:

    [self.collectionView performBatchUpdates:nil completion:nil]

Upvotes: 21

Related Questions