如果 collectionView 有SectionHeader 的时候,调用 scrollToItem 会滚动到第一项,header 无法显示。
collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), at: UICollectionViewScrollPosition(), animated: true)
调用此方法可滚动到组头
// layout 的 header 悬浮属性
layout.sectionHeadersPinToVisibleBounds = true
// 滚动到指定的位置
let selectedIndexPath = IndexPath(item:0 , section: indexPath.row)
if let layoutAttributes = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: selectedIndexPath) {
let headerOffset = CGPoint(x:0, y:layoutAttributes.frame.origin.y - collectionView.contentInset.top)
collectionView.setContentOffset(headerOffset, animated: true)
}
网友评论