iOS UICollectionView 添加headerView分组后滚动到指定的section

方法一:(网上很多都是这样写,但是会有副作用)

[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:index] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];

点击索引后,效果图:

不显示header的效果图

headerView不显示了,被上方搜索框挡住了。

somebody可能说让header悬浮可以解决,于是我们设置layout的sectionHeadersPinToVisibleBounds 属性

layout.sectionHeadersPinToVisibleBounds = YES;

注意:sectionHeadersPinToVisibleBounds 是UICollectionViewFlowLayout的属性,不是collectionView的属性。

我们来看看效果图:

header悬浮的效果图

从图中可以看出,header遮挡住cell了,显然效果依然不好。所以方法一是有局限性的,如果只是一组,指定滚动某个cell可以满足需求。

方法二:

UICollectionViewLayoutAttributes *attributes = [_collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]];
CGRect rect = attributes.frame;
[_collectionView setContentOffset:CGPointMake(_collectionView.frame.origin.x, rect.origin.y - “header的高度”) animated:YES];

效果图:

最终效果

完美解决 。代码也不难理解,希望对你有所帮助。



作者:逍遥晨旭
链接:https://www.jianshu.com/p/340fed801b2e
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值