在 swift 中滚动时,如何阻止 tableview 单元格出现故障和闪烁图像?

How to stop tableview cells from glitching and flickering image when scrolling in swift?

我有一个显示来自 Firebase 的数据的 table 视图。它在 table 视图中显示正常,但是当滚动开始时,table 开始出现故障或让单元格图像和文本重新加载和闪烁,这非常难看。帮助!这是我的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell", for: indexPath) as! MainTableViewCell
func downloadPicture(finished: () -> Void) {
            cell.profilePicture.image = nil
                if let imageUrlString = self.payments[indexPath.row].picture,
                       let imageUrl = URL(string: imageUrlString) {
                        do {
                            let imageData = try Data(contentsOf: imageUrl)
                            cell.profilePicture.image = UIImage(data: imageData)
                            cell.profilePicture.layer.cornerRadius = cell.profilePicture.frame.size.width / 2
                            cell.profilePicture.clipsToBounds = true
                            cell.profilePicture.alpha = 1
                        }
                        catch {
                            print("Error fetching image - \(error)")
                    }
            }
            finished()
    }
    downloadPicture {
        print("success")
}
cell.amountLabel.text = "$\(self.payments[indexPath.row].amount ?? "")"
cell.detailsLabel.text = self.payments[indexPath.row].amount ?? ""
return cell

}

您可以简单地使用 SDWebImage 具有缓存管理和高效使用的异步图像下载器。

:

import SDWebImage

yourImageView.sd_setImage(with: URL(string: "yourImageURLFromFirebase.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

@Lukeksaunders 只需转到 GitHub Kinfisher。这个库包含你想要的所有功能。

import Kingfisher
let url = URL(string: "https://example.com/image.png")
imageView.kf.setImage(with: url)

这个库缓存你的图片

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell", for: indexPath) as! MainTableViewCell
    if let imageUrlString = self.payments[indexPath.row].picture,
       let imageUrl = URL(string: imageUrlString) {
        cell.profilePicture.kf.setImage(with: imageUrl)
    }
    cell.amountLabel.text = "$\(self.payments[indexPath.row].amount ?? "")"
    cell.detailsLabel.text = self.payments[indexPath.row].amount ?? ""
    return cell
}