iOSCollectioView滚动到指定section的方法

CollectioView滚动到指定section的方法

 

项目中的需求:collectionView顶部有一个scrollView组成的标签,点击标签,让collectionView滚动到指定的行,滚动collectionView自动切换到顶部指定的标签

实现方法如下:

1. 保证collectionView全部加载完毕,我这里通过一个bool的标志位来标示
  -(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
  {
        if([indexPath row] == ((NSIndexPath*)[[collectionView indexPathsForVisibleItems] lastObject]).row){
            self.isLoaded = YES;
        }
   }
2. 标签点击了CollectionView滚动到指定行
        if (self.isLoaded) {
            
            // scroll to selected index
            NSIndexPath* cellIndexPath = [NSIndexPath indexPathForItem:0 inSection:index+1];
            UICollectionViewLayoutAttributes* attr = [self.collectionView.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:cellIndexPath];
            UIEdgeInsets insets = self.collectionView.scrollIndicatorInsets;
            
            CGRect rect = attr.frame;
            rect.size = self.collectionView.frame.size;
            rect.size.height -= insets.top + insets.bottom;
            CGFloat offset = (rect.origin.y + rect.size.height) - self.collectionView.contentSize.height;
            if ( offset > 0.0 ) rect = CGRectOffset(rect, 0, -offset);
            
            [weakSelf.collectionView scrollRectToVisible:rect animated:YES];
        }
3. CollectionView滚动到指定行的时候,同时切换标签滚动
    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
        static NSInteger currentIndex = 0;

        NSInteger index=scrollView.contentOffset.y;
        CGRect visibleRect = (CGRect){.origin = self.collectionView.contentOffset, .size = self.collectionView.bounds.size};
        CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
        NSIndexPath *visibleIndexPath = [self.collectionView indexPathForItemAtPoint:visiblePoint];
//        NSLog(@"%@",visibleIndexPath);
        if (currentIndex == visibleIndexPath.section || visibleIndexPath == nil) {
            return;
        }
        currentIndex = visibleIndexPath.section;

       [self.itemTool itemScrollToPositionWithIndex:currentIndex isJump:YES];
    }
posted @   孙富有(iOS工程师)  阅读(1202)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
点击右上角即可分享
微信分享提示