dasPing February 2016

Cell is being overzealously reused

I have a UICollectionViewController and some cells (UICollectionViewCell). I want to draw images on some of the cells. This works fine, but when I scroll, some of the cells seems to be being unnecessarily reused, in other words cells which I didn't explicitly drawn on are being drawn on (only after scrolling).

In my cell I do the following:

imageView = UIImageView(frame: CGRectMake((self.bounds.size.width/4)-1, (self.bounds.size.height/4)-1, 30, 30));
imageView!.image = imageTick
self.addSubview(self.lblDay)
self.addSubview(imageView!)

I create an image view and set its image then add the label and image view.

Does anyone see what I am doing wrong?

Just of the case of completeness here is how I initialise the images for the cell:

let imageTick:UIImage = UIImage(named: "star")!
var imageView:UIImageView? = nil

Answers


Will M. February 2016

UICollectionViewCells are reused by the system, so you need to handle the possibility of a cell being reused in the prepareForReuse method in UICollectionViewCell, by clearing everything from the cell (setting the image to nil etc.)

Here is the doc for UICollectionReusableView that declares that

Here is the doc for UICollectionView You can see in that doc, for the method dequeueReusableCellWithReuseIdentifier:forIndexPath: it talks about calling prepareForReuse if there is an available cell to reuse.

Post Status

Asked in February 2016
Viewed 2,136 times
Voted 4
Answered 1 times

Search




Leave an answer