Paging UICollectionView by cells, not screen

前端 未结 22 2134
予麋鹿
予麋鹿 2020-12-04 05:00

I have UICollectionView with horizontal scrolling and there are always 2 cells side-by-side per the entire screen. I need the scrolling to stop at the begining

22条回答
  •  旧时难觅i
    2020-12-04 05:45

    Kind of like evya's answer, but a little smoother because it doesn't set the targetContentOffset to zero.

    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
        if ([scrollView isKindOfClass:[UICollectionView class]]) {
            UICollectionView* collectionView = (UICollectionView*)scrollView;
            if ([collectionView.collectionViewLayout isKindOfClass:[UICollectionViewFlowLayout class]]) {
                UICollectionViewFlowLayout* layout = (UICollectionViewFlowLayout*)collectionView.collectionViewLayout;
    
                CGFloat pageWidth = layout.itemSize.width + layout.minimumInteritemSpacing;
                CGFloat usualSideOverhang = (scrollView.bounds.size.width - pageWidth)/2.0;
                // k*pageWidth - usualSideOverhang = contentOffset for page at index k if k >= 1, 0 if k = 0
                // -> (contentOffset + usualSideOverhang)/pageWidth = k at page stops
    
                NSInteger targetPage = 0;
                CGFloat currentOffsetInPages = (scrollView.contentOffset.x + usualSideOverhang)/pageWidth;
                targetPage = velocity.x < 0 ? floor(currentOffsetInPages) : ceil(currentOffsetInPages);
                targetPage = MAX(0,MIN(self.projects.count - 1,targetPage));
    
                *targetContentOffset = CGPointMake(MAX(targetPage*pageWidth - usualSideOverhang,0), 0);
            }
        }
    }
    

提交回复
热议问题