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

Fme*_*ina 14 ios uicollectionview uicollectionviewcell

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

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

因为UICollectionViewLayout,我正在使用CHTCollectionViewWaterfallLayout

要异步下载图像我正在使用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 ...}];
Run Code Online (Sandbox Code Playgroud)

题:

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

Ash*_*row 27

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

[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];
                          }];
                      }];
Run Code Online (Sandbox Code Playgroud)

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

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

  • 解决了.实际上,细胞框架没有任何作用.我只需要在animateWithDuration块之前设置cell.imageView框架.`[cell.imageView setFrame:CGRectMake(2,2,image.size.width,image.size.height])]; [UIView animateWithDuration:0.3f动画:^ {[self.collectionView.collectionViewLayout invalidateLayout]; }];` (2认同)