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 习近平为何强调这三个关键词 7904851
- 2 耿爽这段话的含金量还在飙升 7808423
- 3 特大暴雨要来了 7713261
- 4 为什么这一纪念不能忘却 7616055
- 5 你的手机信号变成5G-A了吗 7523400
- 6 卫健委发文 大批医院要开设新科室 7425935
- 7 印度称摧毁巴第二大城市防空系统 7328124
- 8 比尔盖茨:20年内捐出几乎全部财富 7237389
- 9 肖战王一博登4月沸点人物榜 7138423
- 10 看一揽子金融政策如何稳市场稳预期 7044546