代码之家  ›  专栏  ›  技术社区  ›  YosiFZ

每行3个项目的uiCollectionViewCell大小

  •  0
  • YosiFZ  · 技术社区  · 7 年前

    我正在尝试创建一个 UICollectionView 每行3张图片。

    首先,我使用了以下代码:

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

    它看起来不错,但只适用于iPhone X屏幕: enter image description here

    然后我尝试使用此代码,这样它将每行放置3个单元格:

    - (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;
    }
    

    但是,视图开始看起来不同了: enter image description here

    这是单元初始化方法:

    - (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;
    }
    

    你知道这个观点有什么问题吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Gereon    7 年前

    这看起来您没有考虑到布局的 minimumInteritemSpacing . 计算项宽度的公式应为

    float cellWidth = (screenWidth - 2.0 * minimumInteritemSpacing) / 3.0;
    
        2
  •  0
  •   Divya Thakkar    7 年前

    必须提供集合视图单元格之间的最小间距。你 正在使用CollectionViewLayout,因此必须提供如下最小间距。

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

    在这里,您可以通过编程方式提供单元格之间的最小间距(如10)。