iOSCollectioView滾動到指定section的方法

來源:互聯網
上載者:User

標籤: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的方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.