前言
作为一个资深(自认为)iOS程序猿,会经常用到轮播图,上一次使用UIScrollView实现无限轮播的效果,这一次在Swift语言中,我使用UICollectionView再为大家讲解一次无限轮播的实现原理。
先上图:
UICollectionView-无限轮播.gif
首先需要实现了就是UICollectionView的分页,这个很简单:
collectionView.isPagingEnabled = true
接下来就是原理,在UICollectionView的两端需要先添加两张图片,首段需要添加最后一张图片,而尾端需要添加第一张图片,然后在中间的位置上一次添加各个图片。这个其实是很容易实现的:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell
/// 给图片赋值(在首尾分别添加两张图片)
if (indexPath.row == 0) {
cell.imageName = imageNameList.last
} else if (indexPath.row == self.imageNameList.count + 1) {
cell.imageName = imageNameList.first
} else {
cell.imageName = imageNameList[indexPath.row - 1]
}
return cell
}
这样在滑动的时候,通过偏移量就可以实现无限轮播的效果了。当滑动停止时判断偏移量,当偏移量为0时(视图上显示的是最后一张图片),这时候就直接调动调整偏移量的方法,把UICollectionView偏移到最后一张图片的位置。滑动到尾端时是同理。











