下载内部图像后调整UICollectionView单元格的大小

问题描述:

我正在构建UICollectionView,我的自定义单元格将包含两个标签和一个图像.

I'm building a UICollectionView and my custom cells will contain two labels and one image.

每个图像都是异步下载的,因此在下载完成之前我不知道它的大小. 下载完成后,我想调整每个单元格以重新排列其内容和框架,以适应刚下载的图像的高度.

Each image is downloaded asynchronously so I don't know it's size until the download it's complete. Once is downloaded, I want to adapt each cell to re-layout it's content and frame to fit in height the image just downloaded.

作为UICollectionViewLayout,我正在使用 CHTCollectionViewWaterfallLayout

要异步下载图片,我使用的是 SDWebImage

To download the image asynchronously I'm using SDWebImage, like this:

    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                          completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) 
                                {... some completion code here ...}];

问题:

下载图像后立即调整每个UICollectionViewCell大小的正确方法是什么?

What is the right approach to resize each UICollectionViewCell right after the image is downloaded?

当图像返回时,您应该只能够使动画块中的集合视图布局无效.如果一次完成多个图像完成,事情可能会变得有些复杂,但这应该可行:

You should just be able to invalidate your collection view layout in an animation block when the image comes back. Things might get a little complicated if more than one image finishes completion at once, but this should work:

[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                      completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)^{
                          [UIView animateWithDuration:0.3f animations:^{
                              [self.collectionView.collectionViewLayout invalidateLayout];
                          }];
                      }];

然后仅在适当的委托方法中返回不同的大小.

Then just return a different size in the appropriate delegate method.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return /* a different size if the image is done downloading yet */;
}