【问题标题】:SDWebImage changing images while tableview scrollingSDWebImage 在 tableview 滚动时更改图像
【发布时间】:2017-02-12 08:01:07
【问题描述】:

有一个带有单元格的 TableView,每个单元格中都有一个 ImageView。 我使用 SDWebImage 加载图像并且它工作正常,但是当我快速滚动时 - 我看到单元格中的图像在它成为正确图像之前发生了几次变化。

为什么会这样?我该怎么办?

附言我尝试使用或不使用占位符来获得相同的结果

imageView.sd_setImage(with: URL(string : myImageURL), placeholderImage: UIImage(named: "default.jpg"))

【问题讨论】:

    标签: ios objective-c swift sdwebimage


    【解决方案1】:

    在您的 prepareForReuse() 中尝试添加:

    imageView.sd_cancelCurrentImageLoad()
    

    它会取消之前的图片下载,然后就不会发生了。

    另外,我建议将 sd_setImage 与完成块一起使用,这样您还可以确保它正确加载。

    【讨论】:

    • 你有什么建议在这个完成块中检查?
    • 通常我会添加一个淡入淡出动画来让图像看起来更流畅,当你给图像添加淡入过渡时,用户不会注意到你有硬图像过渡,有时我也检查过如果图像与对象匹配(对象在单元格本身的私有初始化程序中被清除)。而且 SDWebImage 的带有完成块的方法效果更好。
    【解决方案2】:

    好吧,请编辑您的反对票,这是我的回答:

        // This will prevent sdwebimage load wrong url
        guard let imgUrl = "Your image url.jpg" else { return }
        imageView.sd_setImage(with: URL(string: imgUrl), placeholderImage: UIImage(named: "Your placeholder image.png"))
    
    
        // Or you can match the url using this code, so the downloader won't catch the wrong url
        if imgUrl == "Your image url" {
            imageView.sd_setImage(with: URL(string: imgUrl), placeholderImage: UIImage(named: "Your placeholder image.png"))
        }
    
    
        // This is will clean your UIImageView, and cancel download progress when cell is not visible (will reuse)
        class YourCell: UITableViewCell {
            override prepareForReuse() {
                imageView.sd_cancelCurrentImageLoad()
                imageView.image = nil
            }
        }
    

    这应该可以解决问题 如果这不能解决您的问题,请提供更多代码,例如您在 cellForRow 索引路径中的代码...

    【讨论】:

    • 您最好将此添加为评论 - 不是答案
    • @moonvader hei 我的答案是否解决了您的问题?如果是,请投票,如果不是,请也投票,因为我已经提供了答案。
    【解决方案3】:

    首先,您可以使用SDWebImage的占位符图像。

    imageView.sd_setImage(with: URL(string: "http://www.domain.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
    

    其次,当单元格被重复使用时,您可以清理图像。

    class YourCell: UITableViewCell {
        override prepareForReuse() {
            // sample code
            imageView.image = nil
        }
    }
    

    【讨论】:

    • 我尝试结合您建议的两种方法,但是当我快速滚动时 - 我仍然看到图像发生了几次变化
    • @moonvader 我想知道你为一个单元格设置了多少次图像。
    • 在我的表格的 cellForRowAt 中,我运行函数 getImage(imageView: cell.ImageView, item_id: id) 它需要它应该找到图像的图像视图和项目的 ID,之后它使用 sd_setImage 加载图像到这个图像视图
    【解决方案4】:

    使用

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

    代替

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! NewsTableViewCell
    

    希望它能解决您的问题。由于 Cell 的可重用性,它正在重复

    【讨论】:

    • 虽然您的诊断是正确的,但这并不是问题的解决方案。单元重用是一种很好的优化技术,因此您应该尝试使用它,而不是绕过它。
    猜你喜欢
    • 1970-01-01
    • 2013-03-29
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2023-04-03
    相关资源
    最近更新 更多