如何实时获取collectionView的当前部分编号

3
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSIndexPath *path = [self.collectionView indexPathForItemAtPoint:CGPointMake(self.collectionView.contentOffset.x, self.collectionView.contentOffset.y)];
    NSLog(@"sectionNumber===%ld",path.section);

// 菜单button滚动到相应的位置
   [self.menuButtonView scrollToButtonWithButtonNumber:path.section];
}

控制台一直显示"sectionNumber===0",但实际上应该是1到10。我不知道自己哪里出了错,而且我已经设置了collectionView的代理。这已经浪费了我3个小时,真的需要帮忙。


1
  1. contentOffset 已经是一个 CGPoint,所以你可以直接将其传递给 indexPathForItemAtPoint
  2. 你确定 contentOffset 实际上有一个项目吗?也许它是在边距之内的一个点。
- Avi
你确定你有多个部分或者你是在寻找path.row吗? - Nirav D
3个回答

2
经过半天的艰苦尝试,我终于解决了这个问题。解决这个问题的关键是CollectionView的两个代理函数:
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath

并且

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(nonnull UICollectionReusableView *)view forElementOfKind:(nonnull NSString *)elementKind atIndexPath:(nonnull NSIndexPath *)indexPath

通过这两个委托函数,您可以正确地获取当前节。


1
在scrollViewDidScroll方法中,您可以获取集合视图中所有可见单元格的索引路径,然后获取中间索引路径并获取其部分。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSArray *indexPaths = [self.mainImageCollection indexPathsForVisibleItems];
    NSIndexPath *middleIndexPath = [indexPaths objectAtIndex:([indexPaths count]/2)];//you must check if indexPaths >=2 or <2
    NSLog(@"indexPath : %d at Section :%d",middleIndexPath.item,middleIndexPath.section);
}

我希望这能有所帮助!


1
请问您能否详细解释一下? - Lantranduc

0
希望这能帮到你。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
   NSIndexPath *centerCellIndexPath = [self.collectionView indexPathForItemAtPoint:[self.view convertPoint:[self.view center] toView:self.collectionView]];
   NSLog(@"Index:%ld",(long)centerCellIndexPath.row);     
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接