【问题标题】:How to stop tableview cells from glitching and flickering image when scrolling in swift?swift - 快速滚动时如何阻止tableview单元格出现故障和闪烁的图像?
【发布时间】:2023-03-22 18:15:01
【问题描述】:

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

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

}

【问题讨论】:

  • 在滚动上重新加载内容是预期和预期的(甚至是必要的)行为。而不是要求停止它,我会要求修复故障
  • 好的,重新加载似乎是件好事,但这会在加载前短暂显示不同的单元格信息,这似乎违反直觉,并且会暂停/使滚动 UI 出现故障。
  • 谢谢,你是怎么做到的?

标签: ios swift xcode firebase uitableview


【解决方案1】:

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

import SDWebImage

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

【讨论】:

    【解决方案2】:

    @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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      相关资源
      最近更新 更多