iOS开发中实现UICollectionView的分页效果(一页的宽度不够collectionview的宽度)

0.分页.png

如果collectionView的宽度和每个item的宽度一样,那么我们只需要设置collectionView的pagingEnabled属性即可实现分页效果。

自定义UICollectionViewLayout

我们需要重写- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity 这个方法,具体实现

  - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
 CGFloat rawPageValue = self.collectionView.contentOffset.x / self.pageWidth;
 CGFloat currentPage = (velocity.x > 0.0) ? floor(rawPageValue) : ceil(rawPageValue);
 CGFloat nextPage = (velocity.x > 0.0) ? ceil(rawPageValue) : floor(rawPageValue);
 BOOL pannedLessThanAPage = fabs(1 + currentPage - rawPageValue) > 0.5;
 BOOL flicked = fabs(velocity.x) > [self flickVelocity];
 if (pannedLessThanAPage && flicked) {
   proposedContentOffset.x = nextPage * self.pageWidth;
 } else {
   proposedContentOffset.x = round(rawPageValue) * self.pageWidth;
 }
 return proposedContentOffset;
}

快速滑动

为了让分页滑动效果和原生分页效果一样,我们需要设置collectionView的decelerationRate的属性为UIScrollViewDecelerationRateFast否则collectionView在滑动的时候特别缓慢。

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

返回值决定了collectionView停止滚动时最终的偏移量(contentOffset)

附上demo地址:https://github.com/yangguanghei/UICollectionView-Page

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

友情链接更多精彩内容