Apple_Magic
Apple_Magic

Reputation: 477

iOS UICollectionvView cell different layout for landscape and portrait

I want make screen in which collection view Cell should fill whole width of screen while device is in portrait , and when device rotates collection view shows 2 cells in 1 section.

For better visualisation see below image.

enter image description here

enter image description here

I tried to make cell width = device width (for portrait) but in landscape cell shows in centre of screen.

Will it possible to make such design using collection view ? If it is possible then how do I achieve this? OR any other idea will be appreciated.

Upvotes: 2

Views: 1413

Answers (2)

kamil3
kamil3

Reputation: 1252

You can try this

#define kNumberOfCellsInARowPortrait 1
#define kNumberOfCellsInARowLandscape 2

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
   return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication.statusBarOrientation)) {
        CGFloat cellWidth = floor((CGRectGetWidth(collectionView.bounds)-5) / kNumberOfCellsInARowLandscape);
        return CGSizeMake(cellWidth, cellWidth);
    } else {
        CGFloat cellWidth = floor((CGRectGetWidth(collectionView.bounds)-5) / kNumberOfCellsInARowPortrait);
        return CGSizeMake(cellWidth, cellWidth);
    }
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self.collectionView reloadData];
}

Upvotes: 0

MacKentoch
MacKentoch

Reputation: 2456

Use size class to position landscape or portrait in different ways.

Have a look to this detailled article go to Add constraints for generic size class

Upvotes: 1

Related Questions