【iOS】UICollectionView

學(xué)習(xí)文章

使用UICollectionView

一 初步UICollectionView

使用UICollectionView的流程:
  1. 設(shè)定一個(gè)UICollectionViewFlowLayout

  2. 使用這個(gè)設(shè)定的UICollectionViewFlowLayout來(lái)初始化UICollectionView

  3. 設(shè)置代理對(duì)象

  4. 繼承UICollectionViewCell設(shè)定重用的cell

效果
?初步效果.png
源碼:

LargeUICollectionViewFlowLayout

import UIKit

class LargeUICollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    override init() {
        
        super.init()
        
        // 單元格尺寸
        self.itemSize                = CGSize(width: 70, height: 70)
        // section 內(nèi)間距
        self.sectionInset            = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25)
        // 橫排單元格最小間距
        self.minimumInteritemSpacing = 40
        // 單元格最小行間距
        self.minimumLineSpacing      = 5
        // CollectionView滾動(dòng)方向
        self.scrollDirection         = .Vertical
    }

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

}  

ShowCollectionViewCell

import UIKit

let identifier = "Identifier"

class ShowCollectionViewCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        self.backgroundColor = UIColor.redColor()
    }

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

ViewController

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var collectionView: UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()

        // 初始化UICollectionView并指定一個(gè)UICollectionViewFlowLayout
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: LargeUICollectionViewFlowLayout())
        collectionView?.registerClass(ShowCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: identifier)
        collectionView?.dataSource = self
        collectionView?.delegate   = self
        
        view.addSubview(collectionView!)
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        return 5
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    
        return 3
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)
        
        return cell
    }


}  
重要的參數(shù)
重要的參數(shù).png

二 實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求

效果
實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求.gif
源碼

修改ShowCollectionViewCell

import UIKit

let identifier = "Identifier"

class ShowCollectionViewCell: UICollectionViewCell {
    
    var showImageView: UIImageView?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        self.backgroundColor = UIColor.whiteColor()
        
        var rect: CGRect = self.bounds
        rect.origin.x    += 3
        rect.origin.y    += 3
        rect.size.width  -= 6
        rect.size.height -= 6
        
        showImageView = UIImageView(frame:rect)
        
        self.addSubview(showImageView!)
        
        
    }

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

修改ViewController

import UIKit

let sourceUrl = "http://www.duitang.com/album/1733789/masn/p/0/100/"

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var collectionView: UICollectionView?
    var dataArray:      [AnyObject]?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化數(shù)據(jù)源
        dataArray = [AnyObject]()

        // 初始化UICollectionView并指定一個(gè)UICollectionViewFlowLayout
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: LargeUICollectionViewFlowLayout())
        collectionView?.registerClass(ShowCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: identifier)
        collectionView?.dataSource = self
        collectionView?.delegate   = self
        
        view.addSubview(collectionView!)
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
            
            // 獲取json數(shù)據(jù)
            let data = NSData(contentsOfURL: NSURL(string: sourceUrl)!)
            
            // 轉(zhuǎn)換數(shù)據(jù)
            if let dataDic = try? NSJSONSerialization.JSONObjectWithData(data!, options: [.MutableContainers, .MutableLeaves]) as! [String : AnyObject]{
            
                let array = dataDic["data"]!["blogs"] as! [AnyObject]
                
                for value in array {
                
                    let temp = value as! [String : AnyObject]
                    
                    print(temp["isrc"])
                    self.dataArray?.append(temp["isrc"]!)
                    
                }
            }
            
            // 主線程更新
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                
                self.collectionView?.reloadData()
            })
        }
        
    }
    
    // MARK: UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        return (self.dataArray?.count)!
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    
        return 3
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ShowCollectionViewCell
        
        cell.showImageView?.sd_setImageWithURL(NSURL(string: self.dataArray![indexPath.row] as! String))
        
        return cell
    }


}

  

三 實(shí)時(shí)更換layout

效果
更換layout.gif
源碼
import UIKit

class AnotherCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override init() {
        
        super.init()
        
        // 單元格尺寸
        self.itemSize                = CGSize(width: 150, height: 200)
        // section 內(nèi)間距
        self.sectionInset            = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25)
        // 橫排單元格最小間距
        self.minimumInteritemSpacing = 40
        // 單元格最小行間距
        self.minimumLineSpacing      = 5
        // CollectionView滾動(dòng)方向
        self.scrollDirection         = .Vertical
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}  
代碼調(diào)整
?代碼調(diào)整1.png
?代碼調(diào)整2.png

四 下載源碼

下載源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末坎穿,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子嗓节,更是在濱河造成了極大的恐慌咧叭,老刑警劉巖履婉,帶你破解...
    沈念sama閱讀 216,402評(píng)論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件欠啤,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡斋竞,警方通過(guò)查閱死者的電腦和手機(jī)钻蔑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)啥刻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人咪笑,你說(shuō)我怎么就攤上這事可帽。” “怎么了窗怒?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,483評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵映跟,是天一觀的道長(zhǎng)蓄拣。 經(jīng)常有香客問(wèn)我,道長(zhǎng)努隙,這世上最難降的妖魔是什么球恤? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,165評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮荸镊,結(jié)果婚禮上咽斧,老公的妹妹穿的比我還像新娘。我一直安慰自己躬存,他們只是感情好张惹,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著优构,像睡著了一般。 火紅的嫁衣襯著肌膚如雪雁竞。 梳的紋絲不亂的頭發(fā)上钦椭,一...
    開(kāi)封第一講書(shū)人閱讀 51,146評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音碑诉,去河邊找鬼彪腔。 笑死,一個(gè)胖子當(dāng)著我的面吹牛进栽,可吹牛的內(nèi)容都是我干的德挣。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼快毛,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼格嗅!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起唠帝,我...
    開(kāi)封第一講書(shū)人閱讀 38,896評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤屯掖,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后襟衰,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體贴铜,經(jīng)...
    沈念sama閱讀 45,311評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評(píng)論 2 332
  • 正文 我和宋清朗相戀三年瀑晒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了绍坝。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,696評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡苔悦,死狀恐怖轩褐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情玖详,我是刑警寧澤灾挨,帶...
    沈念sama閱讀 35,413評(píng)論 5 343
  • 正文 年R本政府宣布邑退,位于F島的核電站,受9級(jí)特大地震影響劳澄,放射性物質(zhì)發(fā)生泄漏地技。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評(píng)論 3 325
  • 文/蒙蒙 一秒拔、第九天 我趴在偏房一處隱蔽的房頂上張望莫矗。 院中可真熱鬧,春花似錦砂缩、人聲如沸作谚。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)妹懒。三九已至,卻和暖如春双吆,著一層夾襖步出監(jiān)牢的瞬間眨唬,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,815評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工好乐, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留匾竿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,698評(píng)論 2 368
  • 正文 我出身青樓蔚万,卻偏偏與公主長(zhǎng)得像岭妖,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子反璃,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評(píng)論 2 353

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