iosswiftuitableviewprepareforreuse

Reusing cells in UITableView


I have my custom cell 'NewsCell'. It contains my custom view 'ImageMosaicView' (that is just subclass of UIView). I use it to show photos like in post in Facebook. I just pass images' urls to ImageMosaicView's instance, and it loads it and shows.

I have an issue. When I scroll my tableView fast, then images from previous cell appear in new cell for a moment, while new images are loading. But I have no idea how they appear there, because I provided default images. Here is an example

How can I avoid this?

// ImageMosaicView.swift

class ImageMosaicView: UIView {
    @IBOutlet var imageViews: [UIImageView]!

    var urlStrings: [String] = [] {
    didSet {
        for imageView in imageViews {
            if let url = URL(string: urlStrings[i]) {
                imageView.loadImage(url: url)
            }
        }
    }

    // MARK: - Initialization

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let _ = loadViewFromNib()
    }

    // MARK: - Methods

    func loadViewFromNib() -> UIView {
        let bundle = Bundle.init(for: type(of: self))
        let nib = UINib(nibName: "ImageMosaicView", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        view.frame = bounds
        view.autoresizingMask = [
            UIViewAutoresizing.flexibleWidth,
            UIViewAutoresizing.flexibleHeight
        ]
        addSubview(view)
        return view
    }
}

// How I provide urls for images:

// NewsViewController.swift. 'tableView(cellForRow:, indexPath:)

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let news = newsCollection[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewsCell", for: indexPath) as! NewsCell
        //...
        cell.imageMosaicView.urlStrings = news.imageUrlsCollection
        //...
        return cell
    } else {
        return UITableViewCell()
    }
}

Solution

  • The right way to do this is to configure the prepareForReuse() method inside the NewsCell class.

    override func prepareForReuse() {
        super.prepareForReuse()
    
        imageView.image = //Default image
        //Whatever other things you need cleared.
    }
    

    This method is called whenever a tableView dequeues a cell. So any cached data should be cleared here or it will persist in the dequeued cell unless you manually change it before returning it in the cellForRowAt method.