我有一个自定义的 UICollectionView 布局,它会在用户滚动时调整大小。当 header 缩小到某一点时,它开始闪烁。
我猜这个问题是,当 header 收缩时, Collection View 认为它超出了框架并可能将其出队,但随后它计算出它在框架内并重新排队,这可能是导致闪烁的原因。
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
}
}
这是一个显示行为的 gif。请注意它是如何开始正常并开始闪烁的。快速滚动也会产生不良影响。
有什么建议吗?
最佳答案
我认为您的问题与布局代码无关。我复制并尝试在一个简单的示例应用程序中使用您的 CustomLayout,没有明显的闪烁问题。
其他尝试:
- 确保您的
collectionView(viewForSupplementaryElementOfKind:at:)
函数使用collectionView.dequeueReusableSupplementaryView(ofKind:withReuseIdentifier:for:)
正确重用标题 View 。每次都创建一个新的标题 View 可能会导致大量延迟。 - 单元格本身是否有任何复杂的绘图代码?
- 最坏的情况是,您可以尝试使用 Instruments Time Profiler 对应用进行分析,以查看哪些操作占用的 CPU 周期最多(假设丢帧是您的问题)。
关于ios - 以某些值调整大小时, Collection View 标题会闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49992912/