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);
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容