Swift 无限轮播图

简介: ICycleView是一个基于UICollectionView实现的轻量级无限轮播图

ICycleView

ICycleView是一个基于UICollectionView实现的轻量级无限轮播图

效果图

Content

  • [Features]()
  • [Requirements]()
  • [CocoaPods]()
  • [Usage]()

    • [默认滚动视图]()
    • [自定义图片宽度和指示器的位置和颜色]()
    • [自定义Cell-纯代码和Xib创建都支持]()
  • [Implementation]()

    • [实现原理]()
    • [主要代码]()

      • [UICollectionView代理方法]()
      • [循环轮播实现]()
  • [Contact]()
  • [Github]()

Features

  • 支持单张图片
  • 支持滚动图片宽度设置
  • 支持本地图片显示,网路图显示,本地图片和网路图混合显示
  • 支持自定义图片展示Cell(纯代码和Xib创建都支持)
  • 支持UIPageControl具体位置设置
  • 支持UIPageControl显示颜色设置
  • 支持图片点击回调
  • 支持图片滚动回调

Requirements

  • iOS 8.0+
  • Swift 4.0+

CocoaPods

pod 'ICycleView', '~> 1.0.0'

在终端 pod search 'ICycleView' 时若出现 Unable to find a pod with name, author, summary, or description matching 'ICycleView' 错误
请在终端运行
1:pod setup
2:$rm ~/Library/Caches/CocoaPods/search_index.json

Usage

默认滚动视图

效果图

// 惰性初始化滚动视图
lazy var defaultCycleView: ICycleView = {
    let cycleView = ICycleView(frame: CGRect(x: 0, y: 50, width: UIScreen.main.bounds.width, height: 130*scaleForPlus))
    view.addSubview(cycleView)
    return cycleView
}()

// 图片赋值
defaultCycleView.pictures = pictures
自定义图片宽度和指示器的位置和颜色

效果图

// 惰性初始化滚动视图
lazy var customPagetrolPositionnCycleView: ICycleView = {
    let cycleView = ICycleView(frame: CGRect(x: 0, y: 190, width: UIScreen.main.bounds.width, height: 130*scaleForPlus))
    cycleView.imgViewWidth = 374*scaleForPlus
    cycleView.pageIndicatorTintColor = .green
    view.addSubview(cycleView)
    return cycleView
}()

// 图片赋值
customPagetrolPositionnCycleView.pictures = pictures
// pageControlStyle属性必须在设置 pictures 后赋值,因为指示器是根据 numberOfPages 计算Size的
customPagetrolPositionnCycleView.pageControlStyle = .bottom(bottom: -20)
customPagetrolPositionnCycleView.pageControlStyle = .right(trailing: 30*scaleForPlus)
自定义Cell-纯代码和Xib创建都支持

效果图

// 惰性初始化滚动视图
lazy var customPictureCellCycleView: ICycleView = {
    let cycleView = ICycleView(frame: CGRect(x: 0, y: 345, width: UIScreen.main.bounds.width, height: 130*scaleForPlus))
    cycleView.register([UINib.init(nibName: "CustomCycleViewCell", bundle: nil)], identifiers: ["CustomCell"])
    cycleView.delegate = self
    view.addSubview(cycleView)
    return cycleView
}()

// 图片赋值
customPictureCellCycleView.pictures = pictures

// 代理方法

/**
 - 协议方法都是可选方法,根据需要实现即可
 */
// MARK: ICycleViewDelegate
extension ViewController: ICycleViewDelegate {

    // 图片点击
    func iCycleView(cycleView: ICycleView, didSelectItemAt index: Int) {
        print("你点击了第 \(index) 张图片")
    }

    // 图片自动滚动
    func iCycleView(cycleView: ICycleView, autoScrollingItemAt index: Int) {
        print("当前滚动的图片是第 \(index) 张")
    }

    // 自定义Cell
    func iCycleView(cycleView: ICycleView, collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, picture: String) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCycleViewCell
        cell.imgView.kf.setImage(with: URL(string: picture))
        cell.titleLab.text = "自定义Cell\n第 \(indexPath.item) 张图片"
        return cell
    }

}

Implementation

实现原理
  1. collectionView的cell显示两倍数量的图片,展示图片分为两组,默认显示第二组的第一张
  2. 左滑collectionView到第二组最后一张,即最后一个cell时,设置scrollView的contentOffset显示第一组的最后一张,继续左滑,实现了无限左滑
  3. 右滑collectionView到第一组第一张,即第一cell时,设置scrollView的contentOffset显示第二组的第一张,继续右滑,实现了无限右滑
  4. 由2,3实现无限循环
主要代码
UICollectionView代理方法
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension ICycleView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count * 2
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if isCustomCell {
            // 自定义Cell
            return delegate?.iCycleView?(cycleView: self, collectionView: collectionView, cellForItemAt: IndexPath(item: indexPath.item % pictures.count, section: 0), picture: pictures[indexPath.item % pictures.count]) ?? UICollectionViewCell()
        } else {
            // 默认Cell
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ICycleViewConst.cellIdentifier, for: indexPath) as! ICycleViewCell
            cell.configureCell(picture: pictures[indexPath.item % pictures.count], placeholderImage: placeholderImage, imgViewWidth: imgViewWidth)
            return cell
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate?.iCycleView?(cycleView: self, didSelectItemAt: indexPath.item % pictures.count)
    }
    
}
循环轮播实现
// MARK: - 循环轮播实现
extension ICycleView {
    
    // 定时器方法,更新Cell位置
    @objc private func updateCollectionViewAutoScrolling() {
        if let indexPath = collectionView.indexPathsForVisibleItems.last {
            let nextPath = IndexPath(item: indexPath.item + 1, section: indexPath.section)
            collectionView.scrollToItem(at: nextPath, at: .centeredHorizontally, animated: true)
        }
    }
    
    // 开始拖拽时,停止定时器
    public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        timer.fireDate = Date.distantFuture
    }
    
    // 结束拖拽时,恢复定时器
    public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        timer.fireDate = Date(timeIntervalSinceNow: autoScrollDelay)
    }
    
    /**
     - 监听手动减速完成(停止滚动)
     - 1.collectionView的cell显示两倍数量的图片,展示图片分为两组,默认显示第二组的第一张
     - 2.左滑collectionView到第二组最后一张,即最后一个cell时,设置scrollView的contentOffset显示第一组的最后一张,继续左滑,实现了无限左滑
     - 3.右滑collectionView到第一组第一张,即第一cell时,设置scrollView的contentOffset显示第二组的第一张,继续右滑,实现了无限右滑
     - 4.由2,3实现无限循环
     */
    public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let offsetX = scrollView.contentOffset.x
        let page = Int(offsetX / bounds.size.width)
        let itemsCount = collectionView.numberOfItems(inSection: 0)
        if page == 0 {
            // 第一页
            collectionView.contentOffset = CGPoint(x: offsetX + CGFloat(pictures.count) * bounds.size.width, y: 0)
        } else if page == itemsCount - 1 {
            // 最后一页
            collectionView.contentOffset = CGPoint(x: offsetX - CGFloat(pictures.count) * bounds.size.width, y: 0)
        }
    }
    
    // - 滚动动画结束的时候调用
    public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        scrollViewDidEndDecelerating(collectionView)
    }
    
    /**
     - 正在滚动
     - 设置分页,算出滚动位置,更新指示器
     */
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetX = scrollView.contentOffset.x
        var page = Int(offsetX / bounds.size.width+0.5)
        page = page % pictures.count
        if pageControl.currentPage != page {
            pageControl.currentPage = page
            delegate?.iCycleView?(cycleView: self, autoScrollingItemAt: page)
        }
    }
    
}

Contact

QQ: 2256472253
Email: ixialuo@126.com

Github

下载Demo

目录
相关文章
|
3月前
|
安全 编译器 Swift
IOS开发基础知识: 对比 Swift 和 Objective-C 的优缺点。
IOS开发基础知识: 对比 Swift 和 Objective-C 的优缺点。
91 2
|
2月前
|
监控 API Swift
用Swift开发iOS平台上的上网行为管理监控软件
在当今数字化时代,随着智能手机的普及,人们对于网络的依赖日益增加。然而,对于一些特定场景,如家庭、学校或者企业,对于iOS设备上的网络行为进行管理和监控显得尤为重要。为了满足这一需求,我们可以利用Swift语言开发一款iOS平台上的上网行为管理监控软件。
191 2
|
3月前
|
监控 Swift iOS开发
局域网计算机监控软件中利用Swift构建iOS端的移动监控应用
在局域网计算机监控软件的开发中,构建iOS端的移动监控应用是一项关键任务。本文将介绍如何利用Swift语言实现这一目标,通过多个代码示例展示关键功能的实现。
225 1
|
3月前
|
安全 JavaScript 前端开发
IOS开发基础知识:介绍一下 Swift 和 Objective-C,它们之间有什么区别?
IOS开发基础知识:介绍一下 Swift 和 Objective-C,它们之间有什么区别?
65 0
|
5月前
|
JavaScript 前端开发 PHP
用swift开发ios移动端app应用初体验
直接跟着 apple 官方的 SwiftUI 教程跑的,写惯了 javascript 奔放的代码,很多语法理解起来还是有点费劲
57 1
|
7月前
|
Swift iOS开发
iOS OC混编Swift 后者无法走断点
iOS OC混编Swift 后者无法走断点
49 0
|
12月前
|
Swift iOS开发
IOS使用Swift加载Xib文件
IOS使用Swift加载Xib文件
252 0
|
Swift iOS开发
iOS开发 - 适合工程多环境切换(swift环境),适合经常打很多不同环境包的人
iOS开发 - 适合工程多环境切换(swift环境),适合经常打很多不同环境包的人
219 0
iOS开发 - 适合工程多环境切换(swift环境),适合经常打很多不同环境包的人
|
Swift 数据安全/隐私保护 iOS开发
iOS开发 - swift通过Alamofire实现https通信
iOS开发 - swift通过Alamofire实现https通信
345 0
iOS开发 - swift通过Alamofire实现https通信
|
Swift iOS开发 容器
iOS 仿支付宝银行卡界面(支持Swift/OC)
在有支付相关的APP中,都有对应的钱包,虽然现在的支付宝,微信支付很流行,但是都是需要绑定自己的银行卡,那么这个银行卡的卡包页面该怎么实现呢?在网上找了许久也没有找到合适的,那就索性自己造轮子。
324 0