【发布时间】:2017-07-11 00:01:21
【问题描述】:
尝试在(Xcode 9 和 Swift 4)中异步加载 tableView 中的图像,似乎我有一个正确的方法,但如果我快速滚动我的 tableView,我的代码将停止工作。所以基本上我发现了零错误。
这是我的代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
let feed = feeds[indexPath.row]
cell.titleLabel.text = feed.title
cell.pubDateLabel.text = feed.date
cell.thumbnailImageView.image = nil
if let image = cache.object(forKey: indexPath.row as AnyObject) as? UIImage {
cell.thumbnailImageView?.image = image
} else {
let imageStringURL = feed.imageUrl
guard let url = URL(string: imageStringURL) else { fatalError("there is no correct url") }
URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
if let data = try? Data(contentsOf: url!) {
DispatchQueue.main.async(execute: {
guard let image = UIImage(data: data) else { fatalError("can't create image") }
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell // fast scroll issue line
updateCell.thumbnailImageView.image = image
self.cache.setObject(image, forKey: indexPath.row as AnyObject)
})
}
}).resume()
}
return cell
}
我有问题在线:
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
如果我慢慢向下滚动,一切正常,不会出现任何错误。
有谁知道我哪里出错了?
【问题讨论】:
-
为什么不删除该行,将 updateCell 更改为单元格,返回一个占位符单元格,用户可以在其中看到它正在加载,并添加一个完成处理程序,该处理程序将在下载后更改单元格的图像?
-
@J.Doe 该行检查单元格是否可见,正如我所理解的那样,因为如果我不使用该行,我会看到图像在找到要显示的合适图像时一直在变化。跨度>
-
我认为您应该在 CustomTablieViewCell 上使用 prepareForReuse 函数。并将图像设置回零。
-
我不知道是否有任何特定原因不使用其中一个库(Alamofire-Image)[github.com/Alamofire/AlamofireImage](Kingfisher)[github.com/onevcat/Kingfisher] 只是设置了 url 和占位符跨度>
-
@mihatel 只是想了解基础知识
标签: ios swift uitableview asynchronous cell