简体   繁体   中英

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

UICollectionViewCell s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM