SDWebImage + UITableViewCell, wrong image when scrolling?

ⅰ亾dé卋堺 提交于 2019-12-03 03:06:17

If you have your UITableViewDelegate set on your table, you could use the delegate method:

- tableView:didEndDisplayingCell:forRowAtIndexPath:

to set the image to NULL (or the default) when your cell scrolls off screen.

And since you're using SDWebImage, canceling it could be as easy as "cancelCurrentImageLoad" on the cell's image view.

Override prepareForReuse method in your cell class and cancel all loadings there. Do not forget to call super

Example of answer above. Swift 3

func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    (cell as! UITableViewCell).imageView.image = nil
    (cell as! UITableViewCell).imageView.sd_cancelCurrentImageLoad()
}

I was getting blank images with the accepted answer and given the images I'm loading are small, I wanted to let the images cache in the background and not cancel the load.

  1. Push a unique id on the stack before your closure and check it when your closure completes
  2. prepareForReuse

Like this:

func updateArtistImage(url: URL) {
        let _eventId = self.event?.id
        SDWebImageManager.shared().loadImage(with: url, options: [], progress: nil) { (image, data, error, cacheType, finished, url) in
            if self.event!.id == _eventId {
                if error == nil {
                    self.artistImageView.image = image
                } else {
                    self.artistImageView.image = UIImage(named: "error_image")
                }
            }
        }
    }

and this:

override func prepareForReuse() {
    super.prepareForReuse()
    self.artistImageView.image = nil
}

Just call sd_cancelCurrentImageLoad and set [imageView setImage:nil] before call sd_setImageWithURL.

[imageView sd_cancelCurrentImageLoad]; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!