ios - 在此图像上执行某些操作后异步图像加载 - 滚动时图像更改为错误图像

标签 ios swift uitableview

我知道有类似的问题:Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

但我不仅从 URL 加载图像。我有它们,对它们执行一些操作,然后将它们分配给 UIImageView WITHIN UITableViewCell

我是这样做的:

  1. cellForRowAtIndexPath:

    cell.configureCellWithComment(comment)
    
  2. 这些是我单元格中的方法:

    func configureCellWithComment(comment: WLComment) {
    
        if let attachmentUrl = comment.attachmentUrl, let fileName = NSURL(string: attachmentUrl)?.lastPathComponent {
    
            if !NSFileManager.defaultManager().fileExistsAtPath(comment.destinationPathForAttachment().URLByAppendingPathComponent(fileName).path!) {
    
                WLFileClient.sharedClient().downloadFileFrom(attachmentUrl, destinationPath: comment.destinationPathForAttachment(), fileName: fileName, progress: nil, completionBlock: { error in
                    self.attachImageToImageView()
                })
            } else {
                attachImageToImageView()
            }
        }
    }
    

私有(private)方法:

private func attachImageToImageView() {

    if let attachmentUrl = comment.attachmentUrl, let fileName = NSURL(string: attachmentUrl)?.lastPathComponent {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

            let image = WLFileClient.sharedClient().previewImageForFileAtUrl(self.comment.destinationPathForAttachment().URLByAppendingPathComponent(fileName))

            dispatch_async(dispatch_get_main_queue(), {
                self.previewAttachmentButton.enabled = true
                self.attachmentPreviewImageView.image = image
            });
        });
    }
}

我应该怎么做才能解决这个问题?

最佳答案

您的downloadFileFrom 是一个异步方法。因此,当此任务完成时,该单元格可能已被另一行重新使用。因此,在您调用 self.attachImageToImageView() 之前,请检查当前单元格是否在方法启动时服务于同一行。

cellForRowAtIndexPath中,将单元格的标签设置为当前行号。

cell.tag = indexPath.row

现在在您的 configureCellWithComment 方法中,首先将标签存储到一个变量中,然后在异步任务之后检查该变量是否仍然相同:

var tagCache:int = self.tag;

WLFileClient.sharedClient().downloadFileFrom(attachmentUrl, destinationPath: comment.destinationPathForAttachment(), fileName: fileName, progress: nil, completionBlock: {

    if(tagCache==self.tag)
      self.attachImageToImageView()
})

PS:我更习惯于Objective-C,而不是swift,所以如果有语法错误请原谅。

关于ios - 在此图像上执行某些操作后异步图像加载 - 滚动时图像更改为错误图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155483/

相关文章:

iOS:自动布局与 autoresizingMask - 调整整个 View 的大小以填充?

ios - 如何创建一个圆形虚线作为 CALayer?

ios - 如何从 App Delegate 重新加载 UIViewController 数据

ios - 我可以强制 uitableview 中的单元格不在每个部分中从索引 0 开始吗​​?

ios - 将节标题高度和行高设置为 0

ios - 获取当前页码垂直 UIScrollView ios

java - APNS(Apple 推送通知服务器)的反馈服务

ios - 如何使用从左到右的动画和 alpha 0 到 1 进行 segue

swift - Swift 中的 Eureka 库 : How can I loop rows?

ios - UITableViewCell 中点击的 MKMapView 的详细信息