我尝试创建一个UICollectionView
,每行有3张图片。
首先我使用了这段代码:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(110, 110);
}
然后我尝试使用此代码,因此每行将放置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;
}
知道视图的问题是什么?
答案 0 :(得分:1)
您似乎没有考虑布局minimumInteritemSpacing
。计算项目宽度的公式应为
float cellWidth = (screenWidth - 2.0 * minimumInteritemSpacing) / 3.0;
答案 1 :(得分:0)
您必须在集合视图单元格之间提供最小间距。您 正在使用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)。