我使用表dequeueReusableCellWithIdentifier
and afnetworking+uiimageview
。我的一些细胞有图像,有些则没有。如果我在加载图像之前滚动表格,成功块会将图像放入重复使用的错误单元格中。例如,图像位于#2 单元格中,但滚动后它出现在#8 单元格中,因为#8 当时位于第二个位置。是否可以使用setImageWithURLRequest
with dequeueReusableCellWithIdentifier
一起?
My code:
let cell = tableView.dequeueReusableCellWithIdentifier("simpleCell", forIndexPath: indexPath) as UITableViewCell!
cell.textLabel.text = fields[indexPath.row]["name"] as String
cell.imageView.image = nil
if let image = fields[indexPath.row]["image"] as? String {
if (image != "") {
let image_url = NSURL(string: image)
let url_request = NSURLRequest(URL: image_url)
let placeholder = UIImage(named: "no_photo")
cell.imageView.setImageWithURLRequest(url_request, placeholderImage: placeholder, success: { [weak cell] (request:NSURLRequest!,response:NSHTTPURLResponse!, image:UIImage!) -> Void in
if let cell_for_image = cell {
cell_for_image.imageView.image = image
cell_for_image.setNeedsLayout()
}
}, failure: { [weak cell]
(request:NSURLRequest!,response:NSHTTPURLResponse!, error:NSError!) -> Void in
if let cell_for_image = cell {
cell_for_image.imageView.image = nil
cell_for_image.setNeedsLayout()
}
})
}
}
return cell
抱歉,如果我的问题与另一个问题重复。我发现了很多类似的问题,但我还没有找到解决方案。我尝试添加重新加载
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
进入我的成功块,但这没有帮助。
更新:
我还注意到,当我的所有细胞都有图像时,我就没有这个问题。如果我理解正确的话,原因是:当尝试请求新图像时,AFNetworking 正在中止先前对同一单元的请求。但如果我在单元格中没有图像,它就不会中止。我怎样才能手动完成呢?
当单元格被表视图重用时,图像下载仍在后台处理。当它完成时,cell
指向具有不同内容的重复使用的单元格。
您有两个选择:
- Call
cancelImageRequestOperation
在图像视图上之后cell.imageView.image = nil
- 在完成处理程序中,不要引用
cell
;相反,使用您的数据模型从表视图中请求正确的单元格。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)