我是新建的UICollectionView,我有一个问题。我想显示宽度为300px的图像,并计算出正确的高度比例。为此,我做了:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
UIImage *image = [photos objectAtIndex:indexPath.row];
if(image){
UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
float scale = (image.size.height/image.size.width)*300;
[imageView setFrame:CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, 300, scale )];
[cell addSubview:imageView];
cell.backgroundColor = [UIColor clearColor];
}else{
cell.backgroundColor = [UIColor redColor];
}
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
UIImage *image = [photos objectAtIndex:indexPath.row];
float scale = (image.size.height/image.size.width)*300;
return CGSizeMake(300, scale);
}
这似乎在开始时起作用,但是当我向下滚动时,图像开始彼此重叠。这有什么办法可以避免这种情况吗?
答案 0 :(得分:1)
您必须在UICollectionView中调整单元格大小,使用UICollectionViewFlowLayout
查看Ray Wenderlich教程:http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12