我正在尝试调整单元格高度以适应UIImages,问题是看起来UIImage似乎没有填充collectionView单元格。正如你在这个
上看到的那样图片:http://oi61.tinypic.com/98d3zd.jpg
看起来细胞已调整,但图像填充不正确以填充细胞?
cellheights 首先,我创建了一个循环,如果cellWidth为140,则计算新的高度,这是所有情况。
for (int i = 0; i < [homesDic count]; i++) {
UIImage *originalImage = [[homesDic objectAtIndex:i] objectForKey:@"image"];
CGFloat originalHeight = originalImage.size.height;
CGFloat originalWidth = originalImage.size.width;
CGFloat wantedWidth = 140;
float wantedHeight = (originalHeight*wantedWidth)/originalWidth;
[_cellHeights addObject:@(wantedHeight)];
}
然后我将一个imageView插入到collectionView单元格中,并设置框架并将单元格高度设置为等于cellHight数组中的imageheight。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
FRGWaterfallCollectionViewCell *waterfallCell = [collectionView dequeueReusableCellWithReuseIdentifier:WaterfallCellIdentifier indexPath];
waterfallCell.lblTitle.text = [NSString stringWithFormat: @"Item %d", indexPath.item];
waterfallCell.bottomView.backgroundColor = [UIColor colorWithRed:0.184 green:0.192 blue:0.196 alpha:0.7];
waterfallCell.homeImage.image = [[homesDic objectAtIndex:indexPath.item] objectForKey:@"image"];
waterfallCell.homeImage.frame = CGRectMake(0, 0, [self.cellHeights[indexPath.item] floatValue], waterfallCell.frame.size.width);
return waterfallCell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView
layout:(FRGWaterfallCollectionViewLayout *)collectionViewLayout
heightForItemAtIndexPath:(NSIndexPath *)indexPath {
return [[self.cellHeights objectAtIndex:indexPath.item] floatValue];
}
答案 0 :(得分:1)
要设置单元格大小,您应该使用collectionView:layout:sizeForItemAtIndexPath方法,试试这个:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
// Get reference to your image base on indexPath here (I assume you have one section and indexPath.row refer to right image) adjust if needed:
UIImage *originalImage = [[homesDic objectAtIndex: indexPath.row] objectForKey:@"image"];
CGSize imgSize = originalImage.size;
//Adjust if needed
imgSize.height += 20;
imgSize.width += 20;
return imgSize;
}
如果您需要单元格,页眉和页脚之间的间距,请使用以下方法:
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(20, 10, 20, 10);
}
希望这就是你要找的东西