Swift純代碼走進(jìn)UICollectionView

2.jpg

Swift對于一門新的iOS編程語言,他的崛起是必然的

我們這群老程序員們學(xué)習(xí)新的技能也是必然的

不接受新技能將被這大群體無情的淘汰

So 我欣然接受這門看似不成熟的語言

下面我們說說Swift中比較常見的控件UICollectionView

首先我們設(shè)置一個(gè)全局的UICollectionView和一個(gè)數(shù)據(jù)源

var colltionView : UICollectionView?

var dataArr = NSMutableArray()

然后設(shè)置UICollectionView的3個(gè)代理

UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

接下來我們要做的是override func viewDidLoad()方法中初始化一些必要的對象


override func viewDidLoad() {
    super.viewDidLoad()
    var layout = UICollectionViewFlowLayout()
    colltionView = UICollectionView(frame: CGRectMake(0, 0, width, height), collectionViewLayout: layout)
    //注冊一個(gè)cell
    colltionView! .registerClass(Home_Cell.self, forCellWithReuseIdentifier:"cell")
    //注冊一個(gè)headView
    colltionView! .registerClass(Home_HeadView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "headView")
    colltionView?.delegate = self;
    colltionView?.dataSource = self;

    colltionView?.backgroundColor = UIColor.whiteColor()
    //設(shè)置每一個(gè)cell的寬高
    layout.itemSize = CGSizeMake((width-30)/2, 250)
    self.view .addSubview(colltionView!)
    self .getData()
}

然后我們實(shí)現(xiàn)UICollectionView的代理方法

//返回多少個(gè)組
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

    return 1
}
//返回多少個(gè)cell
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return dataArr.count
}
//返回自定義的cell
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! Home_Cell
    var model = GoodsModel()
    model = dataArr[indexPath.row] as! GoodsModel
    let url : NSURL = NSURL(string: model.image_url as String)!
    cell.imgView!.hnk_setImageFromURL(url)
    cell.layer.borderWidth = 0.3;
    cell.layer.borderColor = UIColor.lightGrayColor().CGColor
    cell.titleLabel!.text = model.short_name
    cell.priceLabel!.text = "¥"+model.p_price
    cell.readLabel!.text = "??"+model.like_count
    return cell
}
//返回HeadView的寬高
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHe
aderInSection section: Int) -> CGSize{

    return CGSize(width: width, height: height/1.6)
}


//返回自定義HeadView或者FootView,我這里以headview為例
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{
    var v = Home_HeadView()
    if kind == UICollectionElementKindSectionHeader{

    v = colltionView!.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "headView", forIndexPath: indexPath) as! Home_HeadView
    }
    return v
}
//返回cell 上下左右的間距
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{
    return UIEdgeInsetsMake(5, 10, 5, 10)
}

然后我們來獲取數(shù)據(jù),這里的話我用的是Alamofire進(jìn)行的網(wǎng)絡(luò)請求,URL不方便透露

//獲取數(shù)據(jù)
func getData(){
    Alamofire.request(.GET, GoodsUrl).responseJSON() { (req, _, JSON, _) -> Void in

        if let j = JSON as? NSDictionary{
            var data = j.valueForKey("data")as! NSArray

            for dict in data{
                var model = GoodsModel()
                model.Analytical(dict as! NSDictionary)
                self.dataArr.addObject(model)
            }

            self.colltionView!.reloadData()
        }
    }
}

接下來讓我們看下cell里面究竟寫了些什么玩意


class Home_Cell: UICollectionViewCell {

    let width = UIScreen.mainScreen().bounds.size.width//獲取屏幕寬
    var imgView : UIImageView?//cell上的圖片
    var titleLabel:UILabel?//cell上title
    var priceLabel:UILabel?//cell上價(jià)格
    var readLabel:UILabel?//cell上的閱讀量

override init(frame: CGRect) {

    super.init(frame: frame)
    //初始化各種控件
    imgView = UIImageView(frame: CGRectMake(0, -10, (width-30)/2, 200))
    self .addSubview(imgView!)
    titleLabel = UILabel(frame: CGRectMake(5, CGRectGetMaxY(imgView!.frame)-12, (width-40)/2, 50))
    titleLabel?.numberOfLines = 0
    titleLabel?.font = UIFont.boldSystemFontOfSize(14.0)
    titleLabel?.textColor = UIColor.lightGrayColor()
    self .addSubview(titleLabel!)

    priceLabel = UILabel(frame: CGRectMake(5, CGRectGetMaxY(titleLabel!.frame), (width-40)/2/2, 20))
    priceLabel?.numberOfLines = 0
    priceLabel?.font = UIFont.boldSystemFontOfSize(14.0)
    priceLabel?.textColor = UIColor.lightGrayColor()
    self .addSubview(priceLabel!)

    readLabel = UILabel(frame: CGRectMake((width-30)/2/2, CGRectGetMaxY(titleLabel!.frame), (width-40)/2/2, 20))
    readLabel?.numberOfLines = 0
    readLabel?.textAlignment = NSTextAlignment.Right
    readLabel?.font = UIFont.boldSystemFontOfSize(14.0)
    readLabel?.textColor = UIColor.lightGrayColor()
    self .addSubview(readLabel!)

}

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

}

是不是還覺得缺少點(diǎn)什么?沒錯(cuò),我們的headview是不是還沒整?。?br>
接下來呢,我們看下UICollectionView的headview該怎么設(shè)置

重點(diǎn)在這里!首先headview要繼承UICollectionReusableView

然后我們這個(gè).m文件里面并沒有看到override func viewDidLoad()這樣的方法

那我們怎么辦呢?

接下來就看我的了

我們點(diǎn)到我們繼承的UICollectionReusableView里面去看里面有些什么方法

功夫不負(fù)有心人,??終于找到了一個(gè)可以讓我們用的方法

override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!){

}

我們可以把要自定義的UI 請求數(shù)據(jù)什么的都放這方法里面

也就相當(dāng)于我們VC里面的override func viewDidLoad()這個(gè)方法

教程到結(jié)束

有任何問題可以留言,定期抽時(shí)間回復(fù)

版權(quán)歸?Bison所有 未經(jīng)允許不得轉(zhuǎn)載。

更多經(jīng)驗(yàn)請點(diǎn)擊
原文在:http://www.allluckly.cn/


最終效果圖如下

Swift_CollTionView.gif




推薦一款學(xué)習(xí)iOS開發(fā)的app_____|______| | 傳送門

技術(shù)交流群:534926022(免費(fèi)) 511040024(0.8/人付費(fèi))
版權(quán)歸?Bison所有 如需轉(zhuǎn)載請保留原文超鏈接地址!否則后果自負(fù)!

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

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

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