zoukankan      html  css  js  c++  java
  • 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];
        }
    
    
  • 相关阅读:
    踩坑:windows系统下,nodejs版本管理器无法使用n来管理
    华为,小米部分机型微信浏览器rem不适配的解决方案
    百度地图滚轮缩放时产生位置偏移 问题
    baidu-aip-SDK node.js 身份证识别
    iconfont 怎么在项目中使用图标库
    前端实用功能:选项卡切换
    input复选框操作的部分高频率使用代码
    HTML标签的命名/CSS标准化命名大全
    如何在网页中设置一个定时器计算时间?
    H5JS二维动画制作!two.js的基本操作class2
  • 原文地址:https://www.cnblogs.com/qqcc1388/p/5891665.html
Copyright © 2011-2022 走看看