iOS Swift利用UICollectionView实现无限轮播功能(原理)详解

所属分类: 软件编程 / IOS 阅读数: 756
收藏 0 赞 0 分享

前言

作为一个资深(自认为)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偏移到最后一张图片的位置。滑动到尾端时是同理。

 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
 /// 当UIScrollView滑动到第一位停止时,将UIScrollView的偏移位置改变
 if (scrollView.contentOffset.x == 0) {
  scrollView.contentOffset = CGPoint(x: CGFloat(self.imageNameList.count) * kScreenWidth,y: 0)
  self.pageControl.currentPage = self.imageNameList.count
  /// 当UIScrollView滑动到最后一位停止时,将UIScrollView的偏移位置改变
 } else if (scrollView.contentOffset.x == CGFloat(self.imageNameList.count + 1) * kScreenWidth) {
  scrollView.contentOffset = CGPoint(x: kScreenWidth,y: 0)
  self.pageControl.currentPage = 0
 } else {
  self.pageControl.currentPage = Int(scrollView.contentOffset.x / kScreenWidth) - 1
 }
 }

其实原理很简单,个人认为使用UICollectionView实现无限轮播比起UIScrollView更加实用并且便于维护,接下来我将代码全部列一下:

import UIKit

let kScreenWidth = UIScreen.main.bounds.width

class ViewController: UIViewController {
 
 lazy var collectionView: UICollectionView = {
 let flowLayout = UICollectionViewFlowLayout()
 flowLayout.minimumLineSpacing = 0
 flowLayout.minimumInteritemSpacing = 0
 flowLayout.scrollDirection = .horizontal
 flowLayout.itemSize = CGSize(width: kScreenWidth, height: 200)
 
 let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200), collectionViewLayout: flowLayout)
 
 collectionView.isPagingEnabled = true
 collectionView.showsHorizontalScrollIndicator = false
 collectionView.backgroundColor = UIColor.white
 collectionView.delegate = self
 collectionView.dataSource = self
 self.view.addSubview(collectionView)
 
 return collectionView
 }()
 
 lazy var pageControl: UIPageControl = {
 let pageControl = UIPageControl(frame: CGRect(x: 0, y: 150, width: kScreenWidth, height: 50))
 
 pageControl.numberOfPages = self.imageNameList.count
 pageControl.currentPage = 0
 
 pageControl.tintColor = UIColor.black
 pageControl.pageIndicatorTintColor = UIColor.gray;
 
 return pageControl;
 }()
 
 lazy var imageNameList: [String] = {
 let imageList = ["image0", "image1", "image2", "image3"]
 
 return imageList
 }()

 override func viewDidLoad() {
 super.viewDidLoad()
 
 setupController()
 }
 
 func setupController() {
 /// 设置数据
 collectionView.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "ImageCollectionViewCell")
 
 collectionView.reloadData()
 collectionView.scrollToItem(at: IndexPath(row: 1, section: 0), at: .left, animated: false)
 
 self.view.addSubview(pageControl)
 }

}

extension ViewController: UICollectionViewDataSource {
 
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
 /// 这步只是防止崩溃
 if (imageNameList.count == 0) {
  return 0
 }
 return imageNameList.count + 2
 }
 
 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
 }
 
}

extension ViewController: UICollectionViewDelegate {
 
 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
 /// 当UIScrollView滑动到第一位停止时,将UIScrollView的偏移位置改变
 if (scrollView.contentOffset.x == 0) {
  scrollView.contentOffset = CGPoint(x: CGFloat(self.imageNameList.count) * kScreenWidth,y: 0)
  self.pageControl.currentPage = self.imageNameList.count
  /// 当UIScrollView滑动到最后一位停止时,将UIScrollView的偏移位置改变
 } else if (scrollView.contentOffset.x == CGFloat(self.imageNameList.count + 1) * kScreenWidth) {
  scrollView.contentOffset = CGPoint(x: kScreenWidth,y: 0)
  self.pageControl.currentPage = 0
 } else {
  self.pageControl.currentPage = Int(scrollView.contentOffset.x / kScreenWidth) - 1
 }
 }
 
}

/// collectionView图片的cell
class ImageCollectionViewCell: UICollectionViewCell {
 
 /// 显示的图片
 let imageView = UIImageView()
 var imageName: String? = "" {
 didSet {
  if let name = imageName {
  imageView.image = UIImage(named: name)
  }
 }
 }
 
 override init(frame: CGRect) {
 super.init(frame: frame)
 
 setupCell();
 }
 
 /// 初始化视图
 func setupCell() {
 imageView.frame = self.bounds
 contentView.addSubview(imageView)
 }
 
 required init?(coder aDecoder: NSCoder) {
 fatalError("init(coder:) has not been implemented")
 } 
}

ok,喜欢的话可以点一下收藏哈,用UIScrollView实现轮播的原理在:https://www.jb51.net/article/148185.htm,大家需要的话也可以了解一下。

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

更多精彩内容其他人还在看

详解优化iOS程序性能的25个方法

本篇文章主要介绍了优化iOS程序性能的25个方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解iOS开发中解析JSON中的boolean类型的数据遇到的问题

这篇文章主要介绍了详解iOS开发中解析JSON中的boolean类型的数据遇到的问题,具有一定的参考价值,有兴趣的可以了解一下。
收藏 0 赞 0 分享

iOS中模态Model视图跳转和Push视图跳转的需求实现方法

这篇文章主要介绍了iOS中模态Model视图跳转和Push视图跳转的需求实现,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS+PHP注册登录系统 iOS部分(下)

这篇文章主要介绍了iOS+PHP注册登录系统的iOS部分,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

详解iOS - ASIHTTPRequest 网络请求

本篇文章主要介绍了iOS - ASIHTTPRequest 网络请求 ,详细的介绍了 ASIHTTPRequest的使用,具有一定的参考价值,有兴趣的可以了解一下。
收藏 0 赞 0 分享

零基础学习iOS直播之采集

直播的采集由采集的设备(摄像头、话筒)不同分为视频采集和音频采集,本篇文章会分别介绍,需要的朋友一起来看下吧
收藏 0 赞 0 分享

iOS自带动画效果的实例代码

本文给大家分享ios自带动画效果的实现代码,非常不错,具有参考借鉴价值,需要的朋友参考下吧
收藏 0 赞 0 分享

零基础学习iOS直播之播放

对于直播来说,客户端主要做两件事情,推流和播放。本篇主要对播放进行详细介绍,需要的朋友一起来看下吧
收藏 0 赞 0 分享

详解iOS中集成ijkplayer视频直播框架

ijkplayer 是一款做视频直播的框架, 基于ffmpeg, 支持Android和iOS,本文将详细的讲一下在iOS中如何集成ijkplayer, 即便以前从没有接触过,按着下面做也可以集成成功!下面跟着小编一起来看下吧
收藏 0 赞 0 分享

iOS 将系统自带的button改装成上图片下文字的样子

这篇文章主要介绍了 iOS 将系统自带的button改装成上图片下文字的样子,代码是通过继承UIButton,然后再重写layoutSubviews方法,对自带的图片和titleLabel进行重新的layout。下面通过本文给大家分享下实现代码
收藏 0 赞 0 分享
查看更多