UICollectionView左右滑动不规则分页效果

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    CGFloat cardWidth = SCREEN_WIDTH - 54;
    BOOL isIndexMinus = velocity.x<0?YES:NO;//向右滑动,索引减小
    CGFloat targetOffsetX = targetContentOffset->x;
    NSInteger currentIndex = self.currentIndex;//scrollView.contentOffset.x/cardWidth;
    //总共列数
    NSUInteger totalColumn = self.dataSource.count;
    NSInteger targetIndex = 0;
    
    //优先判断加速度
    if(ABS(velocity.x)>0.4){
        if(isIndexMinus){
            targetIndex = currentIndex-1;
        }
        else {
            targetIndex = currentIndex+1;
        }
    }
    else {//其次判断偏移量
        if(isIndexMinus){
            targetIndex = (targetOffsetX-cardWidth/2)/cardWidth;
        }
        else {
            targetIndex = (targetOffsetX+cardWidth/2)/cardWidth;
        }
    }//最后校验,防止左右出界
    targetIndex = MAX(0, targetIndex);
    targetIndex = MIN(totalColumn-1,targetIndex);
    targetOffsetX = cardWidth*targetIndex;
    self.currentIndex = targetIndex;
    
    //最后校验,防止左右出界
    targetOffsetX = MAX(targetOffsetX, 0);
    targetOffsetX = MIN(targetOffsetX, (scrollView.contentSize.width-cardWidth));

    *targetContentOffset = CGPointMake(targetOffsetX, targetContentOffset->y);
}

推荐阅读更多精彩内容