UICollectionViewFlowLayout子类导致某些单元格不显示

时间:2014-10-23 20:29:48

标签: ios swift uiscrollview uicollectionview uicollectionviewlayout

我有一个垂直滚动UICollectionView,它使用UICollectionViewFlowLayout的子类来尝试消除项目间距。这会产生类似UITableView的东西,但我需要CollectionView用于其他目的。我的FlowLayout子类的实现存在一个问题,导致单元格在快速滚动时消失。这是我的FlowLayout子类的代码: 编辑:请参阅评论以获取更新

class ListLayout: UICollectionViewFlowLayout {
    override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
        if var answer = super.layoutAttributesForElementsInRect(rect) {
            for attr in (answer as [UICollectionViewLayoutAttributes]) {
                let ip = attr.indexPath
                attr.frame = self.layoutAttributesForItemAtIndexPath(ip).frame
            }
            return answer;
        }
        return nil
    }

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
        let currentItemAtts = super.layoutAttributesForItemAtIndexPath(indexPath) as UICollectionViewLayoutAttributes
        if indexPath.item == 0 {
            var frame = currentItemAtts.frame
            frame.origin.y = 0
            currentItemAtts.frame = frame
            return currentItemAtts
        }
        let prevIP = NSIndexPath(forItem: indexPath.item - 1, inSection: indexPath.section)
        let prevFrame = self.layoutAttributesForItemAtIndexPath(prevIP).frame
        let prevFrameTopPoint = prevFrame.origin.y + prevFrame.size.height
        var frame = currentItemAtts.frame
        frame.origin.y = prevFrameTopPoint
        currentItemAtts.frame = frame
        return currentItemAtts
    }
}

还有一点需要注意:我的细胞高度可变。它们的高度是通过覆盖自定义单元格的子类中的preferredLayoutAttributesFittingAttributes来设置的:

override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes! {
    let attr: UICollectionViewLayoutAttributes = layoutAttributes.copy() as UICollectionViewLayoutAttributes
    attr.frame.size = CGSizeMake(self.frame.size.width, myHeight)
    return attr
}

我在初始化时设置了布局的估计大小:

flowLayout.estimatedItemSize = CGSize(width: UIScreen.mainScreen().bounds.size.width, height: 60)

这是一个演示此问题的GIF:

Problem

有没有人知道发生了什么?非常感谢您的帮助。

谢谢!

0 个答案:

没有答案