在滚动或重新加载 tableviewcell 之前,UITableView 不显示远程图像

UITableView not showing remote image until scroll or reload of tableviewcell

我正在使用 Kingfisher 下载和缓存远程图像。

我想在 UITableViewCell

中渲染这些图像

目前只有滚动才能显示图像。

我怀疑这是因为初始图像大小为零,一旦我滚动单元格就会重新绘制并渲染图像。

为了解决这个问题,我在 Kingfisher

的完成处理程序中调用了 tableView.reloadRows(at: [indexPath], with: .none)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTableViewCellId", for: indexPath) as! FeedGifCell

    let url = URL(string: items[indexPath.item])!
    let imageView = ImageResource(downloadURL: url, cacheKey: "\(url)-imageview")
    let placeHolderImage = UIImage.from(hex: "ffffff").resize(width: 1, height: 190)
    cell.gifImage.kf.setImage(with: imageView, placeholder: placeHolderImage) { _ in
        tableView.reloadRows(at: [indexPath], with: .none)
    }

    return cell
}

我应用了一个固定高度和宽度的简单占位符,以便在应用图像之前为单元格提供一些高度。

我不确定这是最好的方法,我不喜欢调用 tableView.reloadRows(at: [indexPath], with: .none) 这感觉有点......hacky。

此外,在重新绘制单元格之前,我有白色 space 我的占位符,然后在应用正确的图像/尺寸时跳转。

是否可以简单地阻止单元格在应用图像之前完全不可见?

没有!在某个单元格中的图像完成下载后,您不必以任何方式重新加载 tableView。除此之外,你做的一切都是正确的。我也用翠鸟

但将来,您可以在单元格 class 中创建一个函数,比如 setupCell(_ imageURL: URL?)。无论如何,继续,在你的 cellForRow 方法中,就像这样:

cell.gifImage.kf.setImage(with: imageView, placeholder: placeHolderImage, completionHandler: nil)

现在,如果没有下载图像或者您没有要为 URL 对象制作的图像 URL 字符串,您可以在 Kingfisher 的错误块中捕获它,然后您将需要将您的 error imageUIImage)对象传递给您的 imageView,这样就不会有重复的图像。

例如,我的单元格 setupCell() 函数中有以下内容:

    if let url = vendor.image?.URLEscaped {
        let resource = ImageResource(downloadURL: url, cacheKey: url.absoluteString)
        self.imageView_Vendor.kf.setImage(with: resource, options: [.transition(.fade(0.2)), .cacheOriginalImage])
        return
    }

    self.imageView_Vendor.image = nil

希望对您有所帮助!

编辑:

对于图像高度的处理,这可能会有所帮助: