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 热爱与坚守 7903969
- 2 中核集团重大突破:成功产出第一桶铀 7808329
- 3 第二代居民身份证迎换证高峰 7713789
- 4 这份防中暑秘籍请收好 7615746
- 5 全国唯一做宝剑的专业:就业率近100% 7520152
- 6 十分钟很短但这是她30年的痛苦 7428613
- 7 净网:来看1起侵犯公民个人信息案 7329686
- 8 中山大学133名考生取消录取资格 7239086
- 9 村民捞手机索要1500元未果又扔水里 7138028
- 10 邓紫棋小说首日销售额破4000万 7043259