[英]Cell is being overzealously reused
I have a UICollectionViewController and some cells (UICollectionViewCell). 我有一个UICollectionViewController和一些单元格(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.) UICollectionViewCell
被系统重用,因此您需要通过清除单元格中的所有内容(将图像设置为nil等)来处理UICollectionViewCell
的prepareForReuse
方法中单元格被重用的可能性。
Here is the doc for UICollectionReusableView that declares that 这是UICollectionReusableView的文档,该文档声明
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. 这是UICollectionView的文档,您可以在该文档中看到方法
dequeueReusableCellWithReuseIdentifier:forIndexPath:
如果有可用的单元格,它将讨论调用prepareForReuse
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.