YosiFZ
YosiFZ

Reputation: 7900

UICollectionViewCell size for 3 items per row

I'm trying to create a UICollectionView with 3 images per row.

For the start i used this code:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(110, 110);
}

And it's looking good but it only fits the iPhone X screen: enter image description here

Then i tried to use this code so it will put 3 cells per row:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    float cellWidth = screenWidth / 3.0;
    CGSize size = CGSizeMake(cellWidth, cellWidth);

    return size;
}

But then the view is starting looking different: enter image description here

This is the cell initialize method:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
              cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"TrendingCell";

TrendingCell *cell = (TrendingCell*)[collection dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

TrendingItem * item = [[[TrendingRep sharedTrending] trendingArray] objectAtIndex:indexPath.row];

cell.text.text = item.title;

cell.image.layer.cornerRadius = cell.image.frame.size.width / 2;
cell.image.clipsToBounds = YES;

[cell.image sd_setImageWithURL:[NSURL URLWithString:item.imageUrl]
               placeholderImage:nil
                        options:SDWebImageProgressiveDownload
                      completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {

                          [cell.progressView setHidden:NO];
}];

return cell;
}

Any idea what can be the issue with the view?

Upvotes: 0

Views: 1378

Answers (2)

Pradeep Singh
Pradeep Singh

Reputation: 160

You have to provide minimum spacing between the collection View cell. You are using collectionviewLayout, So you have to provide minimum spacing like below.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(collectionView.frame.size.width/3 - 10, collectionView.frame.size.width/3)
}

Here You can provide minimum spacing (like 10) between cells programmatically.

Upvotes: 0

Gereon
Gereon

Reputation: 17874

This looks like you're not taking into account the layout's minimumInteritemSpacing. The formula to calculate the item's width should be

float cellWidth = (screenWidth - 2.0 * minimumInteritemSpacing) / 3.0;

Upvotes: 1

Related Questions