微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有图像的单元格的 UICollectionView 初始滚动滞后

如何解决带有图像的单元格的 UICollectionView 初始滚动滞后

我有一个垂直滚动的 uicollectionview,它使用子类 uiimageview 加载单元格,该子类通过 url 字符串下载图像。

我的网络调用后台线程中,而且我正在使用缓存,但我不明白为什么滚动时仍然存在初始延迟。任何指导将不胜感激。

    class ViewController: UIViewController {
    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,for: indexPath as IndexPath) as! ACollectionViewCell
        cell.populate(with: url)
        return cell
    }
}

class ACollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: PictureImageView!
    
    func populate(with url: String) {
        imageView.loadImageUsingUrlString(urlString: url)
    }
}

let imageCache = NSCache<Nsstring,UIImage>()

class PictureImageView: UIImageView {
    var imageUrlString: String?
    
    func loadImageUsingUrlString(urlString: String) {
        imageUrlString = urlString
        
        image = #imageLiteral(resourceName: "blank_oval")
        contentMode = .scaleAspectFill
        layer.cornerRadius = frame.width/2
        layer.masksToBounds = true
        
        guard let url = URL(string: urlString) else {
            image = #imageLiteral(resourceName: "blank_oval")
            return
        }
        
        if let imageFromCache = imageCache.object(forKey: urlString as Nsstring) {
            print("Fetched image from cache")
            image = imageFromCache
            return
        }
        
        URLSession.shared.dataTask(with: url) { data,response,error in
        guard error == nil else {
            print("Failed to fetch profile image:",error)
            self.image = #imageLiteral(resourceName: "blank_oval")
            return
        }
            
        dispatchQueue.main.async {
            guard let data = data,let imagetoCache = UIImage(data: data) else {
                self.image = #imageLiteral(resourceName: "blank_oval")
                return
            }
            if self.imageUrlString == urlString {
                dispatchQueue.main.async {
                    self.image = imagetoCache
                }
                
            }
            imageCache.setobject(imagetoCache,forKey: urlString as Nsstring)
        }
        }.resume()
    }
}

解决方法

在过去的 5 年里,我参与的几乎每个项目都使用它。这是远程服务所需图像的防弹实现。

SDWebImage

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。