但我不仅从 URL 加载图像。我有它们,对它们执行一些操作,然后将它们分配给 UIImageView
WITHIN UITableViewCell
。
我是这样做的:
在
内cellForRowAtIndexPath:
cell.configureCellWithComment(comment)
这些是我单元格中的方法:
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/