z22
z22

Reputation: 10083

UICollectionView auto layout with different cells

I am using UICollectionView with autolayout to display gallery. I have 2 types of prototype cells- one to display for 2-columned collectionView and one for 3-columned view.

On button click, the view is to be toggled to 2-columned and 3-columned

Following is my code:

    -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellGrid" forIndexPath:indexPath];
        if([selected_layout isEqualToString:@"tile"]){
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellTile" forIndexPath:indexPath];  // for 2 columns
        } else {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellGrid" forIndexPath:indexPath];  // for 3 columns
        }
[cell layoutIfNeeded];
    [cell setNeedsDisplay];

    return cell;
}

I am not setting cell's height/width anywhere in code, I have just specified it in xib. But everytime 3 columned collectionView is displayed with about 10 pixel black gap between each cell.

I referred this link but it is using swift and custom cell classes. I don't want to use that.

How do I solve this? Where am I getting wrong?

Upvotes: 0

Views: 222

Answers (1)

Mohit Mathur
Mohit Mathur

Reputation: 62

Add these delegate methods:

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionView *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{


        return 5;


}


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

Upvotes: 1

Related Questions