使用我自己的UICollectionViewFlowLayout子类滚动时,UICollectionView项目消失

上下文:我正在使用一个UICollectionView一个photoview。 每个图片都是一个UIImage的单元格。 图像可以有不同的大小,我希望他们填满整个屏幕。 所以我写了一个类来决定每一个UICollectionCell的框架,并让UICollectionCell一个子类为每一个项目请求这个类。

我的UICollectionViewFlowLayoutClass:实现UICollectionViewFlowLayoutClass:

 override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let attributesToReturn = super.layoutAttributesForElementsInRect(rect) as? [UICollectionViewLayoutAttributes] for attributes in attributesToReturn ?? [] { if attributes.representedElementCategory == .Cell { let frame = self.layoutAttributesForItemAtIndexPath(attributes.indexPath).frame attributes.size = frame.size attributes.frame = frame } } return attributesToReturn } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { let curAttributes = super.layoutAttributesForItemAtIndexPath(indexPath) let frame = mazeManager.sizeForItemAtIndex(indexPath, collectionView: collectionView!) curAttributes.size = frame.size curAttributes.frame = frame return curAttributes } 

所以框架要求我的MazeManager返回一个框架。 返回的框架似乎是正确的,他们都适合在UICollectionView。

当我打开我的应用程序时,一切看起来都很好,即使我滚动。 但是当我滚动到一个特定的位置(这个位置感觉是随机的,因为它取决于我testing的图像,但同一组图像的位置是相同的)细胞从我的视野中消失。 当我回滚他们回来。

我已经检查过,如果没有隐藏的细胞,但他们从来没有。

在其他有类似问题的线程上,答案是实现collectionViewContentSize所以我做了:

 override func collectionViewContentSize() -> CGSize { let size = mazeManager.collectionViewContentSize return size.height < collectionView!.frame.size.height ? collectionView!.frame.size : size } 

项目数量不是静态的,在达到视图结束时会增长。 所以这里发生的事情是:pipe理器确定最后一项的Origin.y + Size.Height(+ 10点可以肯定),宽度是UICollectionView的宽度。

仍然所有单元格的框架都在这个方法返回的大小之内。 但是仍然有一些细胞消失或根本不出现。

当我滚动进一步通过UICollectionView,我看到其他细胞位于正确的位置。 所以我认为存在差距,但是stream程仍在继续。 (当出现间隙时,没有调用collectionViewDelegate中缺less的idexpath的项目,例如CollectionView要求项目:1,2,3,4,5,6,12,13,14)。

控制台打印错误的定位,我已经检查,一切都在ContentSize内。 所以我几乎没有select。 任何人都可以解释我的情况发生了什么?

谢谢。

编辑:

当我正在寻找一个解决scheme,我已经find了提到的职位( UICollectionView的单元格消失 ),我已经做了4个步骤中的3个。

 override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } 

我只是在初始化程序中添加了滚动方向:

 override init(){ super.init() scrollDirection = .Vertical } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.scrollDirection = .Vertical } 

不幸的是,这并没有解决我的问题,所以它似乎并不重复。

我不知道为什么,但是当我在init方法中添加下面这行时,它是有效的:

  self.itemSize = CGSize(width: 165,height: 165) 

165是我的细胞的平均高度(我需要使其不那么静态)。 我在这里指定的大小似乎被忽略,因为我在屏幕上看到的大小都在layoutAttributesForItemAtIndexPath计算。

所以没有这个属性设置视图performance奇怪,我仍然不知道原因,但我很高兴它的作品。 (如果有人知道原因,我想听听)