我的 UICollectionView 有多个部分,并且有很长的项目列表和补充标题视图。我需要对特定部分进行动画处理并在视图端口中显示部分标题。尝试使用如下最合适的技术找到节标题的位置,但由于标题视图的高度与估计的初始值不同,结果不正确。当该部分不可见并导致 contentOffset 计算位置错误时,
layoutAttributesForSupplementaryElement
使用估计高度:
if let sectionHeaderPosition = collectionView.layoutAttributesForSupplementaryElement(
ofKind: DocType.reuseIdentifier,
at: .init(item: 0, section: section)
) {
let offsetY = sectionHeaderPosition.frame.origin.y - collectionView.contentInset.top
collectionView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
}
有什么建议吗?
在尝试了许多选项之后,发布非常接近预期结果的最佳方法,可能会帮助其他人:
// 1st step
collectionView.scrollToItem(at: .init(item: 0, section: section), at: .top, animated: true)
collectionView.layoutIfNeeded()
// 2nd step
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
if let `self` = self,
let headerPosition = self.collectionView.layoutAttributesForSupplementaryElement(
ofKind: MyCustomerHeader.reuseIdentifier,
at: .init(item: 0, section: section)
) {
let headerOffsetY = headerPosition.frame.origin.y - self.collectionView.contentInset.top
self.collectionView.setContentOffset(
CGPoint(x: self.collectionView.frame.origin.x, y: headerOffsetY),
animated: false
)
}
}