UITableViewCell在滚动时继续更改其图像



当我滚动表格视图时,表格视图单元格的图像保持更改不正确的图像。

我试过这个。

@IBOutlet weak var imageView: UIImageView!
override prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? MyCustomCell else { return UITableViewCell() }
cell.tag = indexPath.row
if cell.tag == indexPath.row {
// download image
downloadManager.download { (image) in
cell.imageView.image = image
}
}
}

但是,滚动时这仍然不正确的图像。 我该如何解决它??

下载图像(异步(后,您需要检查您的单元格是否与该图像实际相关。

例如,单元格可以重新用于另一个索引路径,因此下载的图像不再正确。

我添加了index(indexPath.row(来下载完成闭包,以便您可以检查cell.tag是否等于索引

downloadManager.download(index: indexPath.row) { (image, index) in
if cell.tag == index {
cell.imageView.image = image
}
}

您可以设置占位符图像来解决此问题。请使用 https://github.com/onevcat/Kingfisher 进行异步图像加载

if let url = URL(string: "url_of_your_image") {
imageView.kf.setImage(with: url)
}

这是从带有显示占位符图像的URL下载和加载图像的工作代码,以使用NSCache加载实际图像。

https://stackoverflow.com/a/51746517/10150796

试试这个:

import UIKit
class CustomViewCell: UITableViewCell {
@IBOutlet weak var imageView: UIImageView!
private var task: URLSessionDataTask?
override func prepareForReuse() {
super.prepareForReuse()
task?.cancel()
imageView.image = nil
}
func configureWith(url string: String) {
guard let url = URL(string: string) else { return }
task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
self.imageView.image = image
}
}
}
task?.resume()
}
}

最新更新