调整某些值时,集合视图标题会闪烁

Ste*_*fan 7 ios uicollectionview swift

我有一个自定义的UICollectionView布局,当用户滚动时会调整大小.当标题在某一点缩小时,它开始闪烁.

我猜测问题是,当标题收缩时,集合视图认为它不在帧中并且可能使其出列但是它会计算出它在帧中并重新排队,这可能是导致闪烁的原因.

class CustomLayout: UICollectionViewFlowLayout, UICollectionViewDelegateFlowLayout {

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    let layoutAttributes = super.layoutAttributesForElements(in: rect) as! [UICollectionViewLayoutAttributes]

    let offset = collectionView!.contentOffset ?? CGPoint.zero

    let minY = -sectionInset.top

    if (offset.y >= minY) {

        let setOffset = fabs(170 - minY)
        let extraOffset = fabs(offset.y - minY)

        if  offset.y <= 170 {

            for attributes in  layoutAttributes {
                if let elementKind = attributes.representedElementKind {
                    if elementKind == UICollectionElementKindSectionHeader {

                        var frame = attributes.frame

                        frame.size.height = max(minY, headerReferenceSize.height - (extraOffset * 1.25))
                        frame.origin.y = frame.origin.y + (extraOffset * 1.25)

                        attributes.frame = frame
                    }
                }
            }

        } else {

            for attributes in  layoutAttributes {
                if let elementKind = attributes.representedElementKind {
                    if elementKind == UICollectionElementKindSectionHeader {

                        var frame = attributes.frame

                        frame.size.height = max(minY, headerReferenceSize.height - (setOffset * 1.25))
                        frame.origin.y = frame.origin.y + (setOffset * 1.25)

                        attributes.frame = frame
                    }
                }
            }
        }
    }
    return layoutAttributes
}

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

这是一个显示行为的gif.注意它是如何开始很好并开始闪烁.快速滚动也具有不希望的效果.

在此输入图像描述

有什么建议?

小智 1

我认为您的问题与布局代码无关。我复制并尝试在一个简单的示例应用程序中使用您的 CustomLayout ,没有明显的闪烁问题。

其他要尝试的事情:

  1. 确保您的collectionView(viewForSupplementaryElementOfKind:at:)函数正确地重用标题视图,使用collectionView.dequeueReusableSupplementaryView(ofKind:withReuseIdentifier:for:))。每次创建新的标题视图可能会导致严重的延迟。
  2. 单元格本身有复杂的绘图代码吗?
  3. 最坏的情况是,您可以尝试使用 Instruments Time Profiler 对应用程序进行分析,以查看哪些操作占用了最多的 CPU 周期(假设丢帧是您的问题)。