原文地址:https://www.cnblogs.com/sunfuyou/p/7460825.html
項(xiàng)目中的需求:collectionView頂部有一個(gè)scrollView組成的標(biāo)簽,點(diǎn)擊標(biāo)簽,讓collectionView滾動(dòng)到指定的行,滾動(dòng)collectionView自動(dòng)切換到頂部指定的標(biāo)簽
實(shí)現(xiàn)方法如下:
- 保證collectionView全部加載完畢,我這里通過(guò)一個(gè)bool的標(biāo)志位來(lái)標(biāo)示
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
if([indexPath row] == ((NSIndexPath*)[[collectionView indexPathsForVisibleItems] lastObject]).row){
self.isLoaded = YES;
}
}
- 標(biāo)簽點(diǎn)擊了CollectionView滾動(dòng)到指定行
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];
}
- CollectionView滾動(dòng)到指定行的時(shí)候,同時(shí)切換標(biāo)簽滾動(dòng)
-(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];
}