Swift 使用CollectionView 實(shí)現(xiàn)圖片輪播封裝就是這樣簡(jiǎn)單

前言: 這篇你可以學(xué)會(huì)自定義視圖,創(chuàng)建collectionView,協(xié)議的使用,定時(shí)器;

自制圖片

先上Demo:Github上封裝好的下載即用, 好用請(qǐng)Star Thanks
首先新建一個(gè)繼承于UIView的視圖, 且用collectionView實(shí)現(xiàn)所以需要簽訂兩個(gè)協(xié)議代碼如下:

let sectionNum: Int = 100 // 區(qū)的數(shù)量
let width =  UIScreen.mainScreen().bounds.size.width // 屏幕寬度
let height = UIScreen.mainScreen().bounds.size.width // 屏幕高度 
// 因?yàn)橐獙?shí)現(xiàn)輪播圖片可以點(diǎn)擊定義一個(gè)協(xié)議
// 協(xié)議
protocol XTCycleViewDelegate {
    func didSelectIndexCollectionViewCell(index: Int)->Void
}
class XTCycleScrollView: UIView, UICollectionViewDelegate, UICollectionViewDataSource{

使用到的變量以及創(chuàng)建視圖

    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以及創(chuàng)建定時(shí)器

    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()
    }

定時(shí)器初始化

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

銷毀定時(shí)器

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

實(shí)現(xiàn)循環(huán)滾動(dòng)

 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, 下面會(huì)貼出自定義cell代碼
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! ZJCustomCycleCell
        // 這個(gè)Label實(shí)現(xiàn)顯示數(shù)字,表示是第幾張圖片
        cell.labelTitle.text = NSString(format: "%d", indexPath.row) as String
        // 這里是圖片賦值
        let url:String = self.images[indexPath.row] as! String
        // 這里我使用的是一個(gè)賦值圖片的三方庫(kù),看自己喜好,為方便我沒有自己寫
        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的數(shù)量
        pageControl.numberOfPages = images.count
        return images.count
    }
    //  重新添加定時(shí)器
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.addTimer()
    }
    // 手動(dòng)滑動(dòng)的時(shí)候銷毀定時(shí)器
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.removeTimer()
    }

設(shè)置當(dāng)前的pagecontrol

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

點(diǎn)擊方法

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)
    }

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

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

實(shí)現(xiàn)代理方法

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

走心文章, 值得點(diǎn)贊 ---文/夏天然后

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

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

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

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