iOS开发实战 - 实现scrollView和collectionView自定义分页
点击上方“iOS开发”,选择“置顶公众号”
关键时刻,第一时间送达!
系统自带的Paging Enabled会把scrollView/collectionView的contentSize平均分割成几部分,每页滑动的距离不能自己控制,如下面的演示图片,每页滑动的距离是 cell.width + space + 下一个cell的一小部分,这里将介绍如何自定义每页滑动的距离,并优雅的运用到自己的项目中

OC版 collectionView自定义分页
部分代码:
#define itemWidth self.width-20-34
#define itemHeight self.height-20
@implementation XXHomeBrandCell
{
NSInteger selectedIndex;
}
- (void)awakeFromNib {
[super awakeFromNib];
[_collectionView registerNib:[UINib nibWithNibName:@"XXHomeBrandItem" bundle:nil] forCellWithReuseIdentifier:@"XXHomeBrandItem"];
selectedIndex = 0;
}
//主要代码
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
CGFloat x = targetContentOffset->x;
CGFloat pageWidth = itemWidth + 20;
CGFloat movedX = x - pageWidth * selectedIndex;
if (movedX < -pageWidth * 0.5) {
// Move left
selectedIndex--;
} else if (movedX > pageWidth * 0.5) {
// Move right
selectedIndex++;
}
if (ABS(velocity.x) >= 2){
targetContentOffset->x = pageWidth * selectedIndex;
} else {
targetContentOffset->x = scrollView.contentOffset.x;
[scrollView setContentOffset:CGPointMake(pageWidth * selectedIndex, scrollView.contentOffset.y) animated:YES];
}
NSLog(@"%ld",selectedIndex);
}
#pragma mark FlowLayoutDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(itemWidth, self.height-20);
}

collectionView xib 1

collectionView xib 2

lowLayout

item/cell
参考:
https://github.com/Silence-GitHub/PageScrollViewDemo/blob/master/PageScrollViewDemo/PageScrollVC.swift
里面包含scrollView和collectionView的自定义分页,不过都是swift版本

作者:Metro追光者
https://www.jianshu.com/p/1aa44dd17236
iOS开发整理发布,转载请联系作者获得授权
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 习近平将发表二〇二六年新年贺词 7904141
- 2 2026年国补政策来了 7808738
- 3 东部战区:开火!开火!全部命中! 7712893
- 4 2026年这些民生政策将惠及百姓 7616985
- 5 小学食堂米线过期2.5小时被罚5万 7519709
- 6 解放军喊话驱离台军 原声曝光 7428214
- 7 为博流量直播踩烈士陵墓?绝不姑息 7327605
- 8 每月最高800元!多地发放养老消费券 7238391
- 9 数字人民币升级 1月1日起将计付利息 7141831
- 10 2026年1月1日起 一批新规将施行 7040675







![INNA奈奈 头上长羽毛啦[喵喵] ](https://imgs.knowsafe.com:8087/img/aideep/2022/6/24/e74f8be9e65af4da4f85be15b4de0058.jpg?w=250)




iOS开发
