【问题标题】:UICollectionViewCell size for 3 items per row每行 3 个项目的 UICollectionViewCell 大小
【发布时间】:2018-05-27 08:25:49
【问题描述】:

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

一开始我使用了这个代码:

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

它看起来不错,但只适合 iPhone X 屏幕:

然后我尝试使用此代码,以便每行放置 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;
}

但是视图开始看起来不同了:

这是单元格初始化方法:

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

知道视图有什么问题吗?

【问题讨论】:

  • 作为一个选项,您可以 IMPL 自定义 FlowLayout - 结合通常的委托调用,可以直接调整每个单元格的大小/位置。值得深思。

标签: ios objective-c iphone uicollectionview


【解决方案1】:

您似乎没有考虑布局的minimumInteritemSpacing。计算项目宽度的公式应该是

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

【讨论】:

    【解决方案2】:

    您必须提供集合视图单元格之间的最小间距。你 正在使用 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)。

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2020-10-30
      相关资源
      最近更新 更多