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

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

每个图像都是asynchronous下载的,所以我不知道它的大小,直到下载完成。 一旦下载,我想调整每个单元格重新布局它的内容和框架,以适应刚刚下载的图像的高度。

作为UICollectionViewLayout ,我正在使用CHTCollectionViewWaterfallLayout

要asynchronous下载图像,我使用SDWebImage ,像这样:

  [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的正确方法是什么?

当图像返回时,您应该能够使animation块中的集合视图布局无效。 如果不止一个图像同时完成,事情可能会变得复杂一些,但是这应该起作用:

 [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]; }]; }]; 

然后只需在相应的委托方法中返回不同的大小。

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

要调整集合视图单元格的大小,可以重新加载集合视图并在方法中dynamic返回集合视图单元格的大小:

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; return [cell size]; } 

在单元格大小为dynamic的情况下,从索引path中获取单元格,并根据图像的大小返回其大小。 我通常为单元格创build一个返回dynamic大小的方法,如上例所示。 您可以使用UIImage的size属性来帮助返回基于图像的大小。

你可以尝试reloadItemsAtIndexPaths:完成加载的单元格。