当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS中无限循环滚动简单处理实现原理分析

iOS中无限循环滚动简单处理实现原理分析

2019年07月24日  | 移动技术网移动技术  | 我要评论

说下原理:

1./*初始化/

+ (instancetype)loopscrollviewwithframe:(cgrect)frame;

将背景collectinview视图初始化设置 代理和数据源 、 布局

2.在激活initwithframe后触发 layoutsubviews

 //默认滚动到要显示的第一张图片
 if (self.imagecollectionview.contentoffset.x == 0) {
  nsindexpath *indexpath = [nsindexpath indexpathforitem:1 insection:0];
  [self scrolltoindexpath:indexpath animated:no];
  self.currentindex = 1;
}

界面展示出来的时候默认 显示 真实下标也就是从1开始

设置真实数据源 imagelist ,然后展示 的 数据源是loopimagelist 这里 呢 多出2个对象,0和末尾,设置时 最后 和 起始,setimagelist如下

- (void)setimagelist:(nsmutablearray *)imagelist {
 _imagelist = imagelist;
 self.loopimagelist = [nsmutablearray arraywitharray:imagelist];
 if (imagelist.count>0) {
  [self.loopimagelist insertobject:[imagelist lastobject] atindex:0];
  [self.loopimagelist addobject:[imagelist objectatindex:0]];
 }
}

核心代码和思路

- (void)scrollviewdidscroll:(uiscrollview *)scrollview {
 cgfloat width = self.bounds.size.width;
 //在loopimagelist中,有n+2个对象,因此index取offset.x/width后的整数
 nsinteger index = scrollview.contentoffset.x/width;
 //这个比值很重要
 cgfloat ratio = scrollview.contentoffset.x/width;
 //从显示的最后一张往后滚,自动跳转到显示的第一张
 if (index == self.loopimagelist.count-1) {
  self.currentindex = 1;
  nsindexpath *indexpath = [nsindexpath indexpathforitem:self.currentindex insection:0];
  [self scrolltoindexpath:indexpath animated:no];
  return;
 }
 //从显示的第一张往前滚,自动跳转到显示的最后一张
 //这里判断条件为contentoffset.x和宽的比值,在往前滚快要结束的时候,能达到无缝切换到显示的最后一张的效果
 if (ratio <= 0.01) {
  self.currentindex = self.imagelist.count;
  nsindexpath *indexpath = [nsindexpath indexpathforitem:self.currentindex insection:0];
  [self scrolltoindexpath:indexpath animated:no];
  return;
 }
 if (self.currentindex != index) {
  self.currentindex = index;
 }
 nslog(@"currentindex = %ld",self.currentindex);
}

这里的原因是为什么呢?

这时候在图滚动 执行代理 监听的时候 ,我们的collectionview有设置 pageenable 分页属性很关键有分页动画。

当偏移量判断 真实的数据显示到了最后一张。也就是8 滚到1的时候 ,设置回滚 ,回到默认位置,且没有动画。

另外一步处理当偏移量 小于 一个极小值 也就是 偏移即将到达 0 的是偶也就是 真实的第一张回滚到最后 一张的时候,设置默认滚动到最后一张。

最重要的一点 这个黑科技 是使用scro 滚动到特定的item所以 在触发的那一时刻,item就设定死了,scrollviewdidscroll:也就不会再滚动,因为现在的偏移量是一个唯一值。

总结

以上所述是小编给大家介绍的ios中无限循环滚动简单处理实现原理分析,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网