【发布时间】:2021-02-09 15:10:00
【问题描述】:
我编写了一个异步方法来将图片加载到 tableview 中。但问题是图像没有加载,因为它不会在滚动后自动更新。我已经尝试添加:
tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
但这只会用不同的图像一直刷新行。第二个问题是滚动后图像会显示,但有时图像会加载到错误的行中。
请有人帮我解决这个问题,因为我无法弄清楚。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell", for: indexPath)
let article = newsArticles!.articles[indexPath.row]
cell.textLabel?.text = article.title
cell.detailTextLabel?.text = article.content
cell.imageView?.image = nil
if let url = article.urlToImage {
imageLoader.obtainImageWithPath(imagePath: url) { (image) in
if let updateCell = tableView.cellForRow(at: indexPath) {
updateCell.imageView?.image = image
tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
}
}
}
return cell
}
图像加载器:
class ImageLoader {
var imageCache = NSCache<NSString, UIImage>()
init() {
self.imageCache = NSCache()
}
func obtainImageWithPath(imagePath: URL, completionHandler: @escaping (UIImage) -> ()) {
if let image = self.imageCache.object(forKey: imagePath.absoluteString as NSString) {
DispatchQueue.main.async {
completionHandler(image)
}
} else {
let placeholder: UIImage = UIImage(named: "placeholderImage")!
DispatchQueue.main.async {
completionHandler(placeholder)
}
let task = URLSession.shared.dataTask(with: imagePath, completionHandler: {data, response, error in
let image: UIImage! = UIImage(data: data!)
self.imageCache.setObject(image, forKey: imagePath.absoluteString as NSString)
DispatchQueue.main.async {
completionHandler(image)
}
})
task.resume()
}
}
}
【问题讨论】:
标签: swift xcode uitableview