62-Swift之輪播圖(UICollectionView)

一、 前言

在現(xiàn)在App中首頁信息展示非常重要观话,那問題就來了频蛔,如何在有限的空間來展示更多的產(chǎn)品信息呢?隨著時(shí)代的進(jìn)步帽驯,App的開發(fā)人員找到了一種能夠滿足首頁信息更多展示的控件--輪播圖尼变。在輪播圖的實(shí)現(xiàn)中多種多樣浆劲,今天我們介紹一個(gè)實(shí)現(xiàn)的方法。使用 UICollectionView來實(shí)現(xiàn)度气,同時(shí)減少內(nèi)存資源的消耗膨报。

二、為什么選擇 UICollectionView 做組件院领?

  • UICollectionView 可以減少內(nèi)存資源的消耗够吩,它是有兩個(gè)Item進(jìn)行展示的。

  • UICollectionView 在Item 滑動(dòng)的過程中十分流暢强法。

  • UICollectionView 可以實(shí)現(xiàn)各種樣式的效果饮怯。

三、本Demo 使用到的知識(shí)點(diǎn)如下

  • UICollectionView 的使用等一系列知識(shí)

  • 對象類型的判斷 (is)

  • 圖像的異步加載

  • 通知的添加和發(fā)出

  • 給一個(gè)類添加一個(gè)代理事件

  • 定時(shí)器的使用

  • UIPageControl 的使用等一些列知識(shí)

  • 如何解決 UICollectionViewCell 的復(fù)用問題

  • 可變數(shù)組的一些對元素的基本操作

四课竣、本 Demo 的實(shí)現(xiàn)效果

Untitled.gif

五置媳、關(guān)鍵代碼的展示

1> UICollectionView的創(chuàng)建

// TODO: 創(chuàng)建 UICollectionView對象
func createCollectionView(_rect:CGRect) -> Void {
    // 創(chuàng)建對象
    collectionView = UICollectionView.init(frame:CGRect.init(x: 0, y: 0, width: _rect.size.width, height: _rect.size.height), collectionViewLayout:self.createFlowLayout())
    // 設(shè)置代理
    collectionView.delegate = self
    collectionView.dataSource = self
    // 隱藏活動(dòng)標(biāo)尺
    collectionView.showsHorizontalScrollIndicator = false
    // 設(shè)置 UICollectionView 分頁滑動(dòng)
    collectionView.isPagingEnabled = true
    // 注冊 cell
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    // 初始讓 UICollectionView 顯示第二個(gè) Item
    collectionView!.scrollToItem(at: IndexPath.init(row: 1, section: 0), at: .centeredHorizontally, animated: true)
    // 進(jìn)行渲染
    self.addSubview(collectionView)
}

2> 布局對象的創(chuàng)建

// TODO: 創(chuàng)建布局對象
func createFlowLayout() -> UICollectionViewFlowLayout {
    // 創(chuàng)建對象
    let flowLayout = UICollectionViewFlowLayout.init()
    // 設(shè)置滑動(dòng)方向
    flowLayout.scrollDirection = .horizontal
    return flowLayout
}

3> UICollectionView 的代理事件的實(shí)現(xiàn)

// MARK: CollectionView的代理事件

// UICollectionView 返回的 Section 的個(gè)數(shù)迂曲,也可以不寫該代理寥袭。默認(rèn)為一
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

// UICollectionView返回的Item個(gè)數(shù)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return (self.handDataArray?.count)!
}

// 設(shè)置 Item 的大小
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return self.bounds.size
}

// 設(shè)置 Item 之間的間隔
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

// 創(chuàng)建和設(shè)置 UICollectionViewCell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // 創(chuàng)建對象
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
    // 防止cell復(fù)用產(chǎn)生
    for item in cell.contentView.subviews {
        item.removeFromSuperview()
    }
    // 創(chuàng)建展示對象
    let cellImageView = UIImageView.init(frame: cell.bounds)
    cellImageView.contentMode = .scaleAspectFit
    cellImageView.image = UIImage.init(named: "defaut.png")
    cellImageView.isUserInteractionEnabled = true
    // 加載圖像
    let temp = self.handDataArray?[indexPath.row]
    self.asynLoadImage(temp: temp!, imageView: cellImageView,index: indexPath)
    cell.contentView.addSubview(cellImageView)
    // 返回創(chuàng)建對象
    return cell
}

// CollectionView 的 Item 點(diǎn)擊事件
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if self.delegate != nil {
        self.delegate?.didSelecdItem(index: indexPath)
    }
}

4> ShufflingViewDelegate 的代理聲明

protocol ShufflingViewDelegate:NSObjectProtocol {
    func didSelecdItem(index:IndexPath) -> Void
}

5> 網(wǎng)絡(luò)異步加載

// MARK: 異步加載圖像
func asynLoadImage(temp:Any,imageView:UIImageView,index:IndexPath) -> Void {
    // 判斷對象的類型
    // UIImage 類型
    if temp is UIImage {
        imageView.image = (temp as! UIImage)
        return
    }
    var tempRequest:Any?
    // URL
    if temp is URL {
        tempRequest = temp as! URL
    }
    if temp is String {
         tempRequest = URL.init(string: temp as! String)
    }
    let request = URLRequest.init(url: tempRequest as! URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
    let session = URLSession.shared
    let dataTask = session.dataTask(with: request, completionHandler: {
        (data, response, error) -> Void in
        if error != nil{
            print(error.debugDescription)
        }else{
            //將圖片數(shù)據(jù)賦予UIImage
            let img = UIImage(data:data!)
            imageView.image = img
            self.handDataArray?.replaceObject(at: index.row, with: img as Any)
        }
    }) as URLSessionTask
    //使用resume方法啟動(dòng)任務(wù)
    dataTask.resume()

6>可變數(shù)組的元素簡單操作

// 處理傳入的數(shù)據(jù)
func handlingData(array:NSArray) -> Int {
    // 初始化可變數(shù)組
    self.handDataArray = NSMutableArray.init(capacity: 0)
    // 判斷是否存在
    if array.count != 0 {
        self.handDataArray = NSMutableArray.init(array: array)
        self.handDataArray?.add(array.firstObject!)
        self.handDataArray?.insert(array.lastObject!, at: 0)
        return array.count
    }
    return 3
}

7> 定時(shí)器的創(chuàng)建

// 定時(shí)器的創(chuàng)建
func createTimer() -> Void {
     timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
        // 獲取 UICollectionView 的水平偏移
        let horizontalOffsetX =  self.collectionView.contentOffset.x
        // 計(jì)算滑動(dòng)的個(gè)數(shù)
        var pageIndex = Int(horizontalOffsetX) / Int(self.bounds.width)
        // 判斷圖像是否是倒數(shù)第二個(gè)
        if pageIndex  == (self.handDataArray?.count)! - 1 {
            // 讓圖像滑動(dòng)到UICollectionView的第二個(gè)Item的位置
            self.collectionView!.scrollToItem(at: IndexPath.init(row: 2, section: 0), at: .centeredHorizontally, animated: false)
            pageIndex = 2
        }else if pageIndex == (self.handDataArray?.count)!-2 {
            pageIndex = 1
            self.collectionView!.scrollToItem(at: IndexPath.init(row: ((self.handDataArray?.count)!-1), section: 0), at: .centeredHorizontally, animated: true)
        }else {
            self.collectionView!.scrollToItem(at: IndexPath.init(row: pageIndex+1, section: 0), at: .centeredHorizontally, animated: true)
            pageIndex = pageIndex + 1
        }
        // 設(shè)置小白點(diǎn)的顯示
        self.pageControl.currentPage = pageIndex - 1
     })
}

8> 小白點(diǎn)的添加

// 小白點(diǎn)的創(chuàng)建
func createPageControl(index:Int) -> Void {
    pageControl = UIPageControl.init(frame: CGRect.init(x: self.bounds.width - 85, y: self.bounds.height - 30, width: 70, height: 20))
    pageControl.numberOfPages = index
    pageControl.currentPageIndicatorTintColor = UIColor.red
    pageControl.pageIndicatorTintColor = UIColor.white
    self.addSubview(pageControl)
}

9> 滑動(dòng)的效果實(shí)現(xiàn)

// CollectionView的滑動(dòng)事件
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    self.createTimer()
    // 獲取 UICollectionView 的水平偏移
    let horizontalOffsetX =  scrollView.contentOffset.x
    // 計(jì)算滑動(dòng)的個(gè)數(shù)
    var pageIndex = Int(horizontalOffsetX) / Int(self.bounds.width)
    // 判斷圖像是否是倒數(shù)第二個(gè)
    if pageIndex == (self.handDataArray?.count)! - 1 {
        // 讓圖像滑動(dòng)到UICollectionView的第二個(gè)Item的位置
        collectionView!.scrollToItem(at: IndexPath.init(row: 1, section: 0), at: .centeredHorizontally, animated: false)
        pageIndex = 1
    }
    if pageIndex == 0 {
        collectionView!.scrollToItem(at: IndexPath.init(row: ((self.handDataArray?.count)!-2), section: 0), at: .centeredHorizontally, animated: false)
        pageIndex = (self.handDataArray?.count)!-2
    }
    // 設(shè)置小白點(diǎn)的顯示
    self.pageControl.currentPage = pageIndex - 1
}

10> 整體的使用

    // 輪播圖的調(diào)用實(shí)現(xiàn)
    override func viewDidLoad() {
        super.viewDidLoad()
        // 編輯數(shù)據(jù)
        let imageArray = NSMutableArray.init(capacity: 0)
        for i in 0..<4 {
            let  str = String.init(format: "%d.jpg",i)
            imageArray.add(UIImage.init(named: str)!)
        }
        let suf = ShufflingView.init(frame: CGRect.init(x: 0, y: 64, width: self.view.frame.width, height: 160),dataArray: imageArray)
        suf.delegate = self
        self.view.addSubview(suf)
        
    }
    
    // MARK:  協(xié)議的實(shí)現(xiàn)
    func didSelecdItem(index: IndexPath) {
         print(index.row)
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末章姓,一起剝皮案震驚了整個(gè)濱河市识埋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌系忙,老刑警劉巖惠豺,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件洁墙,死亡現(xiàn)場離奇詭異,居然都是意外死亡扫俺,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進(jìn)店門骂际,熙熙樓的掌柜王于貴愁眉苦臉地迎上來冈欢,“玉大人,你說我怎么就攤上這事凑耻。” “怎么了类缤?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵餐弱,是天一觀的道長囱晴。 經(jīng)常有香客問我,道長畸写,這世上最難降的妖魔是什么枯芬? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮翅楼,結(jié)果婚禮上真慢,老公的妹妹穿的比我還像新娘理茎。我一直安慰自己,他們只是感情好朗鸠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布础倍。 她就那樣靜靜地躺著,像睡著了一般忆家。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上揭芍,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天卸例,我揣著相機(jī)與錄音,去河邊找鬼姑原。 笑死旦装,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的阴绢。 我是一名探鬼主播呻袭,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼廉侧!你這毒婦竟也來了篓足?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤连舍,失蹤者是張志新(化名)和其女友劉穎涩哟,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體潜腻,經(jīng)...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡融涣,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妓盲。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片专普。...
    茶點(diǎn)故事閱讀 39,754評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖筋粗,靈堂內(nèi)的尸體忽然破棺而出炸渡,到底是詐尸還是另有隱情,我是刑警寧澤买决,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布吼畏,位于F島的核電站,受9級(jí)特大地震影響躲舌,放射性物質(zhì)發(fā)生泄漏性雄。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一约计、第九天 我趴在偏房一處隱蔽的房頂上張望迁筛。 院中可真熱鬧,春花似錦铺然、人聲如沸酒甸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽农尖。三九已至,卻和暖如春助隧,著一層夾襖步出監(jiān)牢的瞬間滑沧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工哩牍, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留令漂,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓荚孵,卻偏偏與公主長得像纬朝,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子玄组,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,654評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,085評論 25 707
  • UICollectionView是我們常說的集合視圖哆致,它在iOS 6中引入患膛,是iOS開發(fā)者中最受歡迎的UI元素之一...
    pro648閱讀 10,669評論 18 44
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件胞此、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,096評論 4 62
  • 外邊的夜是安靜而清冷的 燈光安靜的亮著 指引著回家的行人 家中夜是安靜而溫暖的 書輕輕地展在面前 文字里講述著悲歡...
    遇見更美的自己閱讀 177評論 0 0
  • 第一章 天宮茶市集
    qqminghome閱讀 271評論 0 0