SDWebImage在单元格中重复图像,而不是等待加载。

我正在使用SDWebImage从服务器提取图像到IOS中的我的表视图应用程序。 但问题是,当我在表视图中向下滚动,而不是等待图像加载时,把下载的图像放在表视图的前几行,并重复这些图像,直到结束行,当它下载图像时,它会改变这些重复的图像到该行的实际图像。

NSURL * url = [NSURL URLWithString:string]; SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager downloadImageWithURL:url options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { // progression tracking code } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished,NSURL * url) { if (finished && image ) { NSArray *visibleIndexPaths = [tableView indexPathsForVisibleRows]; if ([visibleIndexPaths containsObject:indexPath]) { cell.myImage.image = image; } } }]; 

实际上,这不是SDWebImage的错误,而是UITableView工作原理。 downloadImageWithURL是一个asynchronous的过程,所以当你的tableView委托/数据源方法被调用时,图像还没有下载,因此cellForRow没有图像显示。 为了克服这个问题,你应该首先检查caching中的图像

 [[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:ImageUrl]] 

如果是,则将图像设置为UIImageView,否则使用downloadImageWithURL下载图像并添加单元格标签(将图像显示为正确的行)

 cell.tag = indexPath.row; 

成功下载首先检查正确的行

 if(cell.tag == indexPath.row){ 

并设置图像到UIImageView.Here是setImage方法。

 -(void)setImage:(SLFirstTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath{ SLFirstTableViewCellItem * slFirstTableViewCellItem = [self.categories objectAtIndex:indexPath.row]; // categories is array of items,replace with yours. NSString *ImageUrl = slFirstTableViewCellItem.imageUrl; //assume image url is in slFirstTableViewCellItem object. cell.tag = indexPath.row; if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:ImageUrl]]){ [cell.imgItem setImage: [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:ImageUrl]]; [self hideProgressView:cell]; }else{ [self showProgressView:cell]; [SDWebImageDownloader.sharedDownloader downloadImageWithURL:[NSURL URLWithString:ImageUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { // progression tracking code } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { if (image && finished) { [[SDImageCache sharedImageCache] storeImage:image forKey:ImageUrl]; // cache image if(cell.tag == indexPath.row){ // check if correct row [cell.imgItem setImage:image]; [self hideProgressView:cell]; } }else{ cell.imgItem.hidden = YES; cell.progressBar.hidden = YES; } }]; } } 

并将showProgressViewhideProgressView方法定义为

 -(void)showProgressView:(SLFirstTableViewCell *)cell { cell.progressText.hidden = NO; cell.progressBar.hidden = NO; cell.imgItem.hidden = YES; [cell.progressBar startAnimating]; [cell.progressText setText:@"Loading Image..."]; } -(void)hideProgressView:(SLFirstTableViewCell *)cell{ cell.progressBar.hidden = YES; cell.progressText.hidden = YES; cell.imgItem.hidden = NO; [cell.progressBar stopAnimating]; } 

最后从cellForRowAtIndexPath方法(在返回单元格之前)调用setImage

 [self setImage:cell atIndexPath:indexPath];