John
John

Reputation: 21

Collection view reusing images while scrolling in swift 2

I'm simply desperate, searched for 6 hours now and can't seem to find an answer.

I have a collection view with images loaded from a remote server and while scrolling the cells are being refreshed with previous images for a few seconds before settling. Tried overriding "prepare for reuse" and setting the imageview image to nil but it is still not working.. Would appreciate an example from someone who got it working,

thanks a lot!

EDIT - ADDING THE CODE

CollectionView:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath:indexPath) as! PictureCell

    cell.pictureCD = GalleryCD().fetchTable()[indexPath.row]

    return cell
}

CollectionViewCell:

class PictureCell: UICollectionViewCell {
@IBOutlet weak var picture: UIImageView!

var pictureCD: NSManagedObject! {
    didSet { self.setupData() }
}

override func prepareForReuse() {
    super.prepareForReuse()

    self.picture.image = nil
    self.picture.setNeedsDisplay() // tried adding after some recommendations
    self.setNeedsDisplay()         // tried adding after some recommendations
}

func setupData(){
    self.picture.image = UIImage(named: "blank")

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        let URL = (NSURL (string: url.pictureSquareGET(picture: self.pictureCD)))!

        let data = NSData(contentsOfURL: URL)!

        dispatch_async(dispatch_get_main_queue()) {
            self.picture.image = UIImage(data: data)
        }
    })
}

}

Upvotes: 2

Views: 3828

Answers (2)

Dhruv Narayan Singh
Dhruv Narayan Singh

Reputation: 655

You can update the prepareForReuse method

override func prepareForReuse() {

    myImageView.image = nil

    super.prepareForReuse()
}

Upvotes: 3

Beau Nouvelle
Beau Nouvelle

Reputation: 7252

Your cells have previous images loaded into them because of cell reuse so you are correct there.

All you should need to do is set the cells image as nil in your cellForItemAtIndexPath BEFORE fetching the updated ones from your server.

Upvotes: 0

Related Questions