Gil
Gil

Reputation: 569

ios uitableview - while scrolling, cells display wrong data before updating with correct data

I have a small problem with displaying data from server in UITableView cells. I have an add that displays a "feed" screen, similar to the main screen on Instagram. Each cell in the feed's UITableView loads and image and some text from the server (from parse.com)

This is my cellForRowAtIndexPath implementation:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(HomeCell.reuseIdentifier(), forIndexPath: indexPath) as HomeCell

    // Configure the cell...
    let obj = tableArray[indexPath.section]
    cell.configureWithObject(obj)

    return cell
}

tableArray is an array of PFObjects

over at the HomeCell class, the configureWithObject methods loads the remote image for this cell using SDWebImage and sets the needed text labels

func configureWithObject(object : PFObject) {

    AppManager.sharedInstance().getTrackDetailsFromPost(object, block: { (error, obj) -> Void in
        if error != nil
        {
            return
        }

        var artworkURL = ""
        if let artworkString = obj?[Column.TracksArtwork.rawValue] as? String {
            artworkURL = artworkString
        }


        self.albumArtwork.sd_setImageWithPreviousCachedImageWithURL(NSURL(string: artworkURL))

        var trackTitle = ""

        if let title = obj?[Column.TracksTitle.rawValue] as? String {
            trackTitle = title
        }

        var trackArtist = ""
        if let artist = obj?[Column.TracksArtist.rawValue] as? String {
            trackArtist = artist
        }

        var trackAlbum = ""
        if let album = obj?[Column.TracksAlbum.rawValue] as? String {
            trackAlbum = album
        }

        self.songNameLabel.text = trackTitle
        self.songDetailsLabel.text = "\(trackArtist) - \(trackAlbum)"

    })
}

The problem: When i scroll through the tableview, i see the wrong image and data on some cells for a split second, then the cell refreshes and displays the correct image and data.

How can i make the scrolling experience smooth and not have the cells keep reloading and refreshing data?

Thanks, Gil.

Upvotes: 0

Views: 4436

Answers (1)

James Frost
James Frost

Reputation: 6990

In your HomeCell class, override the prepareForReuse method, and clear out your imageView:

override func prepareForReuse() {
    super.prepareForReuse()

    self.imageView.image = nil // or set a placeholder image
}

For example.

Upvotes: 10

Related Questions