iOS UICollectionView 在滚动时停在某个item位置上

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/C_calary/article/details/78891724

方法一:实现UIScrollView的代理,然后实现下面这个方法

#pragma mark - UIScrollViewDelegate
//预计出大概位置,经过精确定位获得准备位置
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    CGPoint targetOffset = [self nearestTargetOffsetForOffset:*targetContentOffset];
    targetContentOffset->x = targetOffset.x;
    targetContentOffset->y = targetOffset.y;
}
//计算落在哪个item上
- (CGPoint)nearestTargetOffsetForOffset:(CGPoint)offset
{
    CGFloat pageSize = itemSpacing + itemWidth;
    //四舍五入
    NSInteger page = roundf(offset.x / pageSize);
    CGFloat targetX = pageSize * page;
    return CGPointMake(targetX, offset.y);
}

方法二:重写UICollectionViewFlowLayout

参考文献:http://tech.glowing.com/cn/practice-in-uiscrollview/

猜你喜欢

转载自blog.csdn.net/C_calary/article/details/78891724