2 different cell sizes in UICollectionView Objective C

Yvonne picture Yvonne · Jan 6, 2016 · Viewed 13.9k times · Source

I would like to use UICollectionView, it is possible to create the following layout:

something like that...

As you can see, there are two different sizes of the cell. One is 1/4 of the row, the other is 3/4. Is it possible to create this kind of layout with a UICollectionView?

Would anyone can teach me how to do it??? Or is there any samples??? I have already study many tutorials and reference. But still dont know how to do it..

Thanks!

Answer

nithinbhaktha picture nithinbhaktha · Jan 7, 2016

Well I have hardcoded the item width for the time being (72.0 and 23.0). The rest of 5.0 will be used in interim spacing and edgeInsets. This code will give you exactly what you want.

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

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

#pragma mark - CollectionViewFlowLayout Methods

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize newSize = CGSizeZero;
    newSize.height = 100;

    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    CGSize screenSize = screenBounds.size;

    if(indexPath.item % 4 == 0 || indexPath.item % 4 == 3)
    {
        // Size : 1/4th of screen
        newSize.width = screenSize.width * 0.23;
    }
    else
    {
        // Size : 3/4th of screen
        newSize.width = screenSize.width * 0.72;

    }
    return newSize;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 2.0, 10, 2.0);
}