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