关键方法
layoutAttributesForElementsInRect
思路
在 scrollViewDidScroll 代理方法中即时获取colletionView 当前的偏移量,
,偏移量就是当前展示的cell 的 frame的origin, 再根据偏移量创建一个适当的frame, 然后
使用 layoutAttributesForElementsInRect 方法,获取该frame 中的 布局属性数组,使用其中的布局属性即可获得当前展示到IndexPath 了
代码
/// 这里是水平滚动的colletionView ,所以 使用了x
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (!(scrollView.isTracking || scrollView.isDecelerating) || scrollView != self.collectionView) {
//不是用户滚动的,比如setContentOffset等方法,引起的滚动不需要处理。
return;
}
//用户滚动的才处理
//获取categoryView下面一点的所有布局信息,用于知道,当前最上方是显示的哪个section
//使 第一个cell便宜到距离屏幕边界20的时候选中对应的标题=
CGRect leftRect;
leftRect = CGRectMake(scrollView.contentOffset.x + edge + 1, 0, 1, 100);
UICollectionViewLayoutAttributes *topAttributes = [self.collectionView.collectionViewLayout layoutAttributesForElementsInRect:leftRect].lastObject;
///目前滚动到的分区
NSUInteger currentSection = topAttributes.indexPath.section;
}