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];
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM