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

Aro*_* K. 7 iphone objective-c ios swift

上下文:我使用的UICollectionView是一个photoview.每张照片都是一张细胞UIImage.图像可以有不同的大小,我希望它们填满整个屏幕.所以我写了一个类来确定每个单元的框架,UICollectionCell让一个子UICollectionViewFlowLayout类为每个项目请求该框架为正确的框架.

我的执行情况 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
}
Run Code Online (Sandbox Code Playgroud)

所以框架要求我的MazeManager给出一个框架.返回的帧似乎是正确的,它们都适合UICollectionView.

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

我已经检查过哪些细胞没有被隐藏,但它们从未被隐藏过.

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

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

项目数量不是静态的,而是在到达视图末尾时增长.所以这里发生的是:管理器确定Origin.y +最后一项的Size.Height(确保+10点),宽度是UICollectionView的宽度.

仍然所有单元格的帧都在此方法返回的大小范围内.但仍有一些细胞消失或根本不会出现.

当我进一步滚动UICollectionView时,我看到位于正确位置的其他单元格.所以我的观点存在差距,但流程还在继续.(当出现间隙时,collectionViewDelegate中缺少idex路径的项目没有调用.例如,CollectionView请求项目:1,2,3,4,5,6,12,13,14).

控制台没有打印错误的定位,我已经检查过,一切都在ContentSize中.所以我几乎没有选择权.任何人都能解释一下我的情况吗?

谢谢.

编辑:

当我在寻找解决方案时,我已经找到了上面提到的帖子(UICollectionView的单元格消失了),我已经完成了4个步骤中的3个步骤.

override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
    return true
}
Run Code Online (Sandbox Code Playgroud)

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

override init(){
    super.init()
    scrollDirection = .Vertical
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.scrollDirection = .Vertical
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这并不能解决我的问题,所以它对我来说似乎并不重复.

Aro*_* K. 1

我不知道为什么,但当我在方法中添加以下行时它会起作用init

    self.itemSize = CGSize(width: 165,height: 165)
Run Code Online (Sandbox Code Playgroud)

165 是我的单元格的平均高度(我需要使其不那么静态)。我在这里指定的尺寸似乎被忽略了,因为我在屏幕上看到的尺寸都是在layoutAttributesForItemAtIndexPath.

因此,如果没有设置此属性,视图的行为就会很奇怪,我仍然不知道原因,但我很高兴它有效。(如果有人知道原因,我想听听)