Swift 使用CollectionView 實現圖片輪播封裝就是這樣簡單

前言: 這篇你可以學會自定義視圖,創建collectionView,協議的使用,定時器;

自制圖片

先上Demo:Github上封裝好的下載即用, 好用請Star Thanks
首先新建一個繼承于UIView的視圖, 且用collectionView實現所以需要簽訂兩個協議代碼如下:

let sectionNum: Int = 100 // 區的數量
let width =  UIScreen.mainScreen().bounds.size.width // 屏幕寬度
let height = UIScreen.mainScreen().bounds.size.width // 屏幕高度 
// 因為要實現輪播圖片可以點擊定義一個協議
// 協議
protocol XTCycleViewDelegate {
    func didSelectIndexCollectionViewCell(index: Int)->Void
}
class XTCycleScrollView: UIView, UICollectionViewDelegate, UICollectionViewDataSource{

使用到的變量以及創建視圖

    var delegate: XTCycleViewDelegate?
    var cycleCollectionView: UICollectionView?
    var images = NSMutableArray()
    var pageControl = UIPageControl()
    var flowlayout = UICollectionViewFlowLayout()
    var timer = NSTimer()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.createSubviews(frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

布局必要的UI以及創建定時器

    func createSubviews(frame: CGRect){
        cycleCollectionView = UICollectionView.init(frame: CGRectMake(0, 0, frame.size.width, frame.size.height), collectionViewLayout: flowlayout)
        flowlayout.itemSize = CGSizeMake(frame.size.width, frame.size.height);
        flowlayout.minimumInteritemSpacing = 0;
        flowlayout.minimumLineSpacing = 0;
        flowlayout.scrollDirection = UICollectionViewScrollDirection.Horizontal;
        cycleCollectionView!.backgroundColor = UIColor.lightGrayColor()
        cycleCollectionView!.pagingEnabled = true
        cycleCollectionView!.dataSource  = self
        cycleCollectionView!.delegate = self
        cycleCollectionView!.showsHorizontalScrollIndicator = false
        cycleCollectionView!.showsVerticalScrollIndicator = false
        cycleCollectionView!.registerClass(ZJCustomCycleCell.self, forCellWithReuseIdentifier: "cellId")
        self.addSubview(cycleCollectionView!)
        pageControl = UIPageControl.init(frame: CGRectMake(0, 0, frame.size.width / 2, 30))
        pageControl.center = CGPointMake(frame.size.width / 2, frame.size.height - 20);
        self.addSubview(pageControl);
        self.addTimer()
    }

定時器初始化

func addTimer(){
        let timer1 = NSTimer.init(timeInterval: 2, target: self, selector: "nextPageView", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(timer1, forMode: NSRunLoopCommonModes)
        timer = timer1
    }

銷毀定時器

func removeTimer(){
        self.timer.invalidate()
    }

實現循環滾動

 func returnIndexPath()->NSIndexPath{
        var currentIndexPath = cycleCollectionView!.indexPathsForVisibleItems().last
        currentIndexPath = NSIndexPath.init(forRow: (currentIndexPath?.row)!, inSection: sectionNum / 2)
        cycleCollectionView!.scrollToItemAtIndexPath(currentIndexPath!, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        return currentIndexPath!;
    }
 func nextPageView(){

        let indexPath = self.returnIndexPath()
        var item = indexPath.row + 1;
        var section = indexPath.section;
        if item == images.count {
            item = 0
            section++
        }
        self.pageControl.currentPage = item;
        let nextIndexPath = NSIndexPath.init(forRow: item, inSection: section)
        cycleCollectionView!.scrollToItemAtIndexPath(nextIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }

collectionView Delegate

     // 重用池
     func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 這里使用的自定義cell, 下面會貼出自定義cell代碼
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! ZJCustomCycleCell
        // 這個Label實現顯示數字,表示是第幾張圖片
        cell.labelTitle.text = NSString(format: "%d", indexPath.row) as String
        // 這里是圖片賦值
        let url:String = self.images[indexPath.row] as! String
        // 這里我使用的是一個賦值圖片的三方庫,看自己喜好,為方便我沒有自己寫
        cell.imageView.hnk_setImageFromURL(NSURL.init(string: url)!)
        return cell
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return sectionNum
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 在這里給出了pageControl的數量
        pageControl.numberOfPages = images.count
        return images.count
    }
    //  重新添加定時器
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.addTimer()
    }
    // 手動滑動的時候銷毀定時器
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.removeTimer()
    }

設置當前的pagecontrol

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let page = (Int(scrollView.contentOffset.x) / Int(width)) % images.count
        pageControl.currentPage = page
    }

點擊方法

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        self.delegate?.didSelectIndexCollectionViewCell(indexPath.row)
    }

下面是我在自定義cell中的代碼

    var urlImage: String = ""
    var imageView = UIImageView()
    var labelTitle = UILabel()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.createSubviews(frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func createSubviews(frame: CGRect){
        imageView = UIImageView.init(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
        self.contentView.addSubview(imageView)
        labelTitle = UILabel.init(frame: CGRectMake(10, 10, 30, 30))
        imageView.addSubview(labelTitle)
    }

封裝基本完成了, 下面看看如何使用

        // 創建
        let cycle = XTCycleScrollView.init(frame: CGRectMake(0, 70, width, 175))
        // 要實現點擊需要制定代理人
        cycle.delegate = self;
        // 圖片鏈接數組
        let images: NSMutableArray = ["", "", "", ""]
        // 數組賦值
        cycle.images = images
        self.view.addSubview(cycle)

實現代理方法

func didSelectIndexCollectionViewCell(index: Int) {
        print("\\(index)")
    }

走心文章, 值得點贊 ---文/夏天然后

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,251評論 4 61
  • Swift版本點擊這里歡迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh閱讀 25,571評論 7 249
  • 夜深人靜,會想到這個問題,想的多了,有毛骨悚然的感覺。總覺得,死亡是件好遙遠的事情,又是件好近的事情。或許,我們可...
    小考拉俱樂部閱讀 316評論 2 2
  • 朱金鳳 焦點講師二期 信陽 堅持分享1001天 今天看了武志紅老師的《你就是答案活出獨一無二的自己》只看...
    息縣心協沐風f閱讀 334評論 0 3
  • 前言:軟語輕言總是過耳即忘,辣口辣心才會在疼痛中記得久一點,再久一點。過了三十歲,開始做自己吧。 周六的早上,正準...
    向暖Sally閱讀 485評論 4 1