为 tableviewcell 设置图像会减慢 Swift 中的滚动速度

Setting image for tableviewcell slows scrolling in Swift

我想从 url 加载图像并将其设置为 table 视图单元格。 如果我在没有异步的情况下这样做,它会减慢 table 视图。否则,如果我在异步块中设置某些图像显示不正确并且将被异步更改。

第二种方法 - 异步
table 视图单元格被重复使用,获取图像并更改它需要一些时间。所以在短时间内,tableview cell 显示了之前的图像,但它是不正确的。

DispatchQueue.global(qos: .userInitiated).async {
                var userPhoto: UIImage?

                if let imageUrl = participant?.image {
                    let url = URL(string:imageUrl)
                    if let data = try? Data(contentsOf: url!)
                    {
                        userPhoto = UIImage(data: data)
                    }
                }

                DispatchQueue.main.async {
                    if let userPhoto = userPhoto {
                        self.imageViewOwner.image = userPhoto
                    } else {
                        // Sets default image for profile.
                        self.imageViewOwner.image = UIImage(named: "default")
                    }
                }

            }

你可以试试SDWebImage

self.imageViewOwne.sd_setImage(with: URL(string:imageUrl), placeholderImage: UIImage(named: "default"))

按照 "async" 的方式去做才是正确的。

我建议创建一个单独的 class 来使用 DownloadingService 来启动图像请求,跟踪哪些图像已经下载,哪些还没有。

让您的视图控制器(或您的 Table 视图数据源的任何对象)使用上面的对象获取图像对象(从内存或磁盘缓存;您应该在下载后缓存图像)。如果该对象不可用 - 只需在任何地方使用一些默认图像(它可以是加载指示器图像、用户头像图像等)。

也许您必须创建自定义单元格并覆盖 prepareForReuse() 方法。在那里设置单元格的默认图像,这样就不会在单元格上显示旧的/不正确的图像,以防显示单元格时当前下载仍在进行中。

注意:无论是否使用开源库,步骤都是一样的。