Swift 無限輪播圖

上一篇:iOS12 beta 系統(tǒng)如何在Xcode9.4上真機調(diào)試

ICycleView

ICycleView是一個基于UICollectionView實現(xiàn)的輕量級無限輪播圖

效果圖

Content

Features

  • 支持單張圖片
  • 支持滾動圖片寬度設置
  • 支持本地圖片顯示,網(wǎng)路圖顯示,本地圖片和網(wǎng)路圖混合顯示
  • 支持自定義圖片展示Cell(純代碼和Xib創(chuàng)建都支持)
  • 支持UIPageControl具體位置設置
  • 支持UIPageControl顯示顏色設置
  • 支持圖片點擊回調(diào)
  • 支持圖片滾動回調(diào)

Requirements

  • iOS 8.0+
  • Swift 4.0+

CocoaPods

pod 'ICycleView', '~> 1.0.0'

在終端 pod search 'ICycleView' 時若出現(xiàn) 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 后賦值,因為指示器是根據(jù) numberOfPages 計算Size的
customPagetrolPositionnCycleView.pageControlStyle = .bottom(bottom: -20)
customPagetrolPositionnCycleView.pageControlStyle = .right(trailing: 30*scaleForPlus)
自定義Cell-純代碼和Xib創(chuàng)建都支持
效果圖
// 惰性初始化滾動視圖
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

// 代理方法

/**
 - 協(xié)議方法都是可選方法,根據(jù)需要實現(xiàn)即可
 */
// 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

實現(xiàn)原理
  1. collectionView的cell顯示兩倍數(shù)量的圖片,展示圖片分為兩組,默認顯示第二組的第一張
  2. 左滑collectionView到第二組最后一張,即最后一個cell時,設置scrollView的contentOffset顯示第一組的最后一張,繼續(xù)左滑,實現(xiàn)了無限左滑
  3. 右滑collectionView到第一組第一張,即第一cell時,設置scrollView的contentOffset顯示第二組的第一張,繼續(xù)右滑,實現(xiàn)了無限右滑
  4. 由2,3實現(xiàn)無限循環(huán)
主要代碼
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)
    }
    
}
循環(huán)輪播實現(xiàn)
// MARK: - 循環(huán)輪播實現(xiàn)
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
    }
    
    // 結(jié)束拖拽時,恢復定時器
    public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        timer.fireDate = Date(timeIntervalSinceNow: autoScrollDelay)
    }
    
    /**
     - 監(jiān)聽手動減速完成(停止?jié)L動)
     - 1.collectionView的cell顯示兩倍數(shù)量的圖片,展示圖片分為兩組,默認顯示第二組的第一張
     - 2.左滑collectionView到第二組最后一張,即最后一個cell時,設置scrollView的contentOffset顯示第一組的最后一張,繼續(xù)左滑,實現(xiàn)了無限左滑
     - 3.右滑collectionView到第一組第一張,即第一cell時,設置scrollView的contentOffset顯示第二組的第一張,繼續(xù)右滑,實現(xiàn)了無限右滑
     - 4.由2,3實現(xiàn)無限循環(huán)
     */
    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)
        }
    }
    
    // - 滾動動畫結(jié)束的時候調(diào)用
    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

下一篇:封裝 Core Image 的 API - 延展方式

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,236評論 3 119
  • 發(fā)現(xiàn) 關注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 15,692評論 4 61
  • 意義”讓人舍生忘死,“道理”讓人心甘情愿,“自發(fā)”讓人任勞任怨。 賦予一件事意義,就相當于給人一個非做好不可的理由...
    沁沐閱讀 458評論 0 1
  • 秦滅韓之戰(zhàn),沒有絲毫懸念。 曾經(jīng)的“勁韓”,何以淪落到如此地步?君不明、臣不賢而已。 韓國是七大戰(zhàn)國中土地面積最小...
    木皮叔閱讀 933評論 0 3
  • 冷風又開始在指尖流淌。 我走在街道上,路燈昏黃的光照在我背影更加的凄涼。望著遠處燈紅酒綠,憂愁悄悄的在心底蔓延。 ...
    曹家大小姐閱讀 1,230評論 0 31

友情鏈接更多精彩內(nèi)容