Search code examples
iosobjective-cuicollectionviewuicollectionviewcelluicollectionviewlayout

UICollectionView display 3 items per row


I have a UICollectionView created from storyboard,

I want to have 3 items per row in the view. I managed to do that using the following:

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(collectionView.frame.size.width/3.6 , (collectionView.frame.size.height-100)/2);
}

However, if i have 6 items, i got 2 rows with 3 items each. But when i have 4 items, it will display 2 rows with 2 items each.

Is it possible to display them in 2 rows, the first with 3 items and the second contains only 1?


Solution

  • I know it is so late, but the solution that i am currently using and handled this case was by using KRLCollectionViewGridLayout as below

            KRLCollectionViewGridLayout* aFlowLayout = [[KRLCollectionViewGridLayout alloc]init];
            aFlowLayout.aspectRatio = 1;
            aFlowLayout.sectionInset = UIEdgeInsetsMake(2, 2, 2, 2);
            aFlowLayout.interitemSpacing = 2;
            aFlowLayout.lineSpacing = 2;
            aFlowLayout.numberOfItemsPerLine = 3;
            aFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
            _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.heigh) collectionViewLayout:aFlowLayout];
    

    You can find KRLCollectionViewGridLayout library class using this link