码迷,mamicode.com
首页 > 移动开发 > 详细

iOSCollectioView滚动到指定section的方法

时间:2017-08-31 23:16:44      阅读:614      评论:0      收藏:0      [点我收藏+]

标签:index   pos   ref   指定   组成   com   set   body   ott   

项目中的需求: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];
    }

iOSCollectioView滚动到指定section的方法

标签:index   pos   ref   指定   组成   com   set   body   ott   

原文地址:http://www.cnblogs.com/sunfuyou/p/7460825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!