当我滚动我的tableview时,错误的图像被设置在我的tableview单元格中。 我怎样才能解决这个问题?

当我滚动我的桌面视图时,错误的图像被设置在我的tableview单元格中。 我怎样才能解决这个问题? 以下是我的cellForRowAtIndexPath方法中的相关代码。

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{ UIImage * image = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:self.myURL]]]; dispatch_sync(dispatch_get_main_queue(), ^{ cell.myImageView = image; }); }); return cell; } 

首先检查你的细胞是否不适用,然后设置图像。 在滚动时间重用了以前的单元格。

看下面的代码,它会帮助你。

 static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{ UIImage * image = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:self.myURL]]]; dispatch_sync(dispatch_get_main_queue(), ^{ cell.myImageView = image; }); }); } return cell; 

您的图像数据正在asynchronous下载,但不会在重新使用时取消。

由于UITableViewCells被重用,这些types的asynchronous调用需要在单元重用时被取消,否则当你已经加载新的数据时,它们可以完成。

我的build议是使用像SDWebImage的图书馆来加载你的图片。 它使用比上面列出的代码更less的代码下载,caching和显示图像。

https://github.com/rs/SDWebImage

我对你的代码做了一些修改,我认为它会帮助你

 cell.myImageView = nil; // or cell.myImageView = [UIImage imageNamed:@"placeholder.png"]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:self.myURL]]; NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (data) { UIImage *image = [UIImage imageWithData:data]; if (image) { dispatch_async(dispatch_get_main_queue(), ^{ MyCell *myCell = (id)[tableView cellForRowAtIndexPath:indexPath]; if (myCell) myCell.myImageView = image; }); } } }]; [task resume]; return cell; 

并使cell.myImageView =零; 或在其中设置占位符图像

 - tableView:didEndDisplayingCell:forRowAtIndexPath: 

要么

简单地说,您可以使用SDWebImage作为本教程链接

试试这个代码。 您需要将图像设置为零,当发生错误或图像不是与url中获取的数据

 let request = NSMutableURLRequest.init(URL: NSURL.init(string: "self.myURL")!) let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request){(data, response, error) in if let imageData = data { let image = UIImage.init(data: data!) if((image) != nil) { dispatch_async(dispatch_get_main_queue(), ^{ cell.myImageView = image }); } else { cell.myImageView = nil; } } else { cell.myImageView = nil print(error?.description) } } dataTask.resume(); 

*