collectionView添加section header之后,scrollToItem方法表现不好,滚动之后section的第一行总是露出半截;
用setContentOffset来实现滚动,对于最后一个section,如果不满一屏,就会很尴尬的卡在顶部,一滑动collectionView,这个section就会掉下来,效果不好,最终用scrollRectToVisible完美解决,如下:
guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout,
let layoutAttr = layout.layoutAttributesForItem(at: IndexPath.init(row: 0, section: indexPath.row)) else {
//用scrollToItem滚动的位置不准确,必须用scrollRectToVisible来滚动
collectionView.scrollToItem(at: IndexPath.init(row: 0, section: indexPath.row), at: .top, animated: true)
return
}
let offset = layoutAttr.frame.minY - layout.sectionInset.top - layout.headerReferenceSize.height
collectionView.scrollRectToVisible(CGRect.init(x: 0, y: offset, width: collectionView.width, height: collectionView.height - collectionView.contentInset.bottom - collectionView.contentInset.top), animated: true)//因为是竖向滑动的collectionview,所以我这里只减去了contentInset的bottom和top