Balázs Vincze
Balázs Vincze

Reputation: 357

AutoLayout for UICollectionView Cells

I have an uicollectionview in my app which shows the photos from the camera roll (using AssetsLibrary) in small square cells by using an uiimageview. My problem is that it all looks fine on an iPhone5/5S but there is huge spacing between the cells when running it on an iPhone 6. The question is: How could I make the cells resize themselves so that the spacing stays the same on all devices? (And the cells grow instead).

iPhone 5S

iPhone 6

Upvotes: 0

Views: 856

Answers (2)

Antonioni
Antonioni

Reputation: 578

Make your collection view controller follow the protocol of UICollectionViewDelegateFlowLayout and override the following method. Then you can size your cells based on the size of your view's bounds.

 - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        // Calculate size based on your view's bounds here
    }

Note: If you're also dealing with rotation you'll have to invalidate your collection view layout when the device rotates in order for this method to be called again and recalculate the sizes.

[self.collectionViewLayout invalidateLayout];

Upvotes: 0

Tram Nguyen
Tram Nguyen

Reputation: 463

After set auto layout for UIImageView to make sure that UIImageView will fit to cell and make the adjustments to the cell size from there

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    int cellWidth = (SCREEN_WIDTH - (3 * PADDING)) / 4;
    return CGSizeMake(cellWidth, cellWidth);
}

Upvotes: 1

Related Questions