【轉(zhuǎn)載】iOS CollectioView滾動(dòng)到指定section的方法

原文地址: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)方法如下:

  1. 保證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;
        }
   }
  1. 標(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];
        }
  1. 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];
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容