ios 带分组headerview的UICollectionview滚动到指定位置

方法一:

[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:index] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];

但是此方法有局限.1.在场景复杂的布局上或者多层嵌套布局上效果不是很好,会出现偏差和失效的情况.2.在含有分组头视图的时候,滚动到指定Cell会遮挡到头部分组headerView,如下图情况:

图一

所以此时需要用到方法二:

oc版本:

UICollectionViewLayoutAttributes*attributes = [self.collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]];

CGRectrect = attributes.frame;

[self.collectionView setContentOffset:CGPointMake(self.collectionView.frame.origin.x, rect.origin.y - “headerView的高度”) animated:YES];

swift版:

 let  path =IndexPath.init(row:0, section:5)

 let  attributes =self.collectionView.layoutAttributesForItem(at: path)

 self.collectionView.setContentOffset(CGPoint.init(x: self.collectionView.frame.origin.x, y: (attributes?.frame.origin.y)!-“headerView的高度”), animated: true)

这样就可以完美解决问题。

如果有什么问题,欢迎评论交流~

你可能感兴趣的:(ios 带分组headerview的UICollectionview滚动到指定位置)