avatar
通过CollectionView快速实现一个无限轮播器,基于原生uikit

核心逻辑是在collection的dateSource

1
2
3
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return infiniteSize
}

infiniteSize可以指定一个非常大的值,但不要指定Int.max,会越界崩溃

例如
let infiniteSize = 100000

1
2
3
4
5
6
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCell", for: indexPath)
guard let size = listSize, size > 0 else { return cell}
cell.backgroundColor = colorList[indexPath.row % size]
return cell
}

cell通过对集合取余来控制集合索引
写完之后,现在可以实现向右的无限滑动,目前,但是向左还不行

原理就是通过设置一个很大的数量itemSize,来模拟无限循环的效果

向左的思路是把默认的collection的索引指向itemSize的中间值,这样左右都有infiniteSize/2的数量了

可以在viewDidload中加上

1
2
3
4
5
guard let size = listSize, size > 0 else { return }
let midIndexPath = IndexPath(row: infiniteSize / size / 2 * size, section: 0)
collectionView.scrollToItem(at: midIndexPath,
at: .centeredHorizontally,
animated: false)

size是数据容器的大小,确保index指向容器的第一个

这样就完成了,方法比较取巧,

优点:

  • 快速,方便
  • 由于reuseable的cell并不会占用内存资源
  • 原生实现,易于维护

缺点:

  • 伪无限循环,到了infinitySize上限,就滚不动了