使用SDWebImageManager在UICollectionView中延迟加载图像

在我的方法cellForItemAtIndexPath我有这样的代码:

SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager downloadWithURL:[NSURL URLWithString:coverURL] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { RRRBigItemCell *cell = (RRRBigItemCell *)[collectionView cellForItemAtIndexPath:indexPath]; if (cell) { RRRImageView *coverView = (RRRImageView *)[cell viewWithTag:COVER_TAG]; coverView.image = image; } }]; 

当我启动应用程序,我向下滚动然后一切都OK。 但是当我滚动比已经显示的单元格没有加载图像(单元格==零)。 如果我再次向下滚动问题仍然是显示单元格,只有新的加载图像。 任何想法我做错了什么?

@pawan是正确的,这将是实现SDWebImage最简单的方法。 它基本上是一个UIImage类,所以简单地使用类别方法(setImageWithURL)。

自从你问了几个其他问题;

  1. 在你的代码中,你应该在主线程上设置coverImage.image,而不是在后台。

  2. 检查单元格是否可见,或者在显示内容方面没有什么意义。

  3. 访问单元格时避免循环引用时,创build集合视图的弱引用是一种很好的做法

所以你的代码)可能被写成如下,如果你坚持按照你的方式(使用类别是最好和最简单的方式)

  __weak myCollectionViewController *weakSelf = self; SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager downloadWithURL:[NSURL URLWithString:coverURL] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { dispatch_async(dispatch_get_main_queue(), ^{ if ([weakSelf.collectionView.indexPathsForVisibleItems containsObject:indexPath]) { RRRBigItemCell *cell = (RRRBigItemCell *)[weakSelf.collectionView cellForItemAtIndexPath:indexPath]; RRRImageView *coverView = (RRRImageView *)[cell viewWithTag:COVER_TAG]; coverView.image = image; }; }); }]; 

为什么不试试这个[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

参考SDWebImage

    Interesting Posts