SDWebImage + UITableViewCell, wrong image when scrolling?

前端 未结 5 1895
失恋的感觉
失恋的感觉 2021-02-06 04:08

i\'m having an issue using SDWebImage to load images to a UIImageView inside a custom UITableViewCell. This is my code at the UITableView delegate:

    static NS         


        
相关标签:
5条回答
  • 2021-02-06 04:37

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

    [imageView sd_cancelCurrentImageLoad]; 
    
    0 讨论(0)
  • 2021-02-06 04:42

    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()
    }
    
    0 讨论(0)
  • 2021-02-06 04:45

    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.

    0 讨论(0)
  • 2021-02-06 04:48

    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
    }
    
    0 讨论(0)
  • 2021-02-06 05:01

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

    0 讨论(0)
提交回复
热议问题