美文网首页Swift学习iOS知识收集Swift Dev
Swift纯代码走进UICollectionView

Swift纯代码走进UICollectionView

作者: Bison | 来源:发表于2015-09-19 10:55 被阅读20084次
2.jpg

Swift对于一门新的iOS编程语言,他的崛起是必然的

我们这群老程序员们学习新的技能也是必然的

不接受新技能将被这大群体无情的淘汰

So 我欣然接受这门看似不成熟的语言

下面我们说说Swift中比较常见的控件UICollectionView

首先我们设置一个全局的UICollectionView和一个数据源

var colltionView : UICollectionView?

var dataArr = NSMutableArray()

然后设置UICollectionView的3个代理

UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

接下来我们要做的是override func viewDidLoad()方法中初始化一些必要的对象


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

    colltionView?.backgroundColor = UIColor.whiteColor()
    //设置每一个cell的宽高
    layout.itemSize = CGSizeMake((width-30)/2, 250)
    self.view .addSubview(colltionView!)
    self .getData()
}

然后我们实现UICollectionView的代理方法

//返回多少个组
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

    return 1
}
//返回多少个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)
}

然后我们来获取数据,这里的话我用的是Alamofire进行的网络请求,URL不方便透露

//获取数据
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上价格
    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")
}

}

是不是还觉得缺少点什么?没错,我们的headview是不是还没整啊?

接下来呢,我们看下UICollectionView的headview该怎么设置

重点在这里!首先headview要继承UICollectionReusableView

然后我们这个.m文件里面并没有看到override func viewDidLoad()这样的方法

那我们怎么办呢?

接下来就看我的了

我们点到我们继承的UICollectionReusableView里面去看里面有些什么方法

功夫不负有心人,😄终于找到了一个可以让我们用的方法

override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!){

}

我们可以把要自定义的UI 请求数据什么的都放这方法里面

也就相当于我们VC里面的override func viewDidLoad()这个方法

教程到结束

有任何问题可以留言,定期抽时间回复

版权归©Bison所有 未经允许不得转载。

更多经验请点击
原文在:http://www.allluckly.cn/


最终效果图如下

Swift_CollTionView.gif



推荐一款学习iOS开发的app_____|______| | 传送门

技术交流群:534926022(免费) 511040024(0.8/人付费)
版权归©Bison所有 如需转载请保留原文超链接地址!否则后果自负!

相关文章

网友评论

  • 74cf8659ae9a:不错不错,收藏了。

    推荐下,分库分表中间件 Sharding-JDBC 源码解析 17 篇:http://t.cn/R0UfGFT


  • Waisti:群拒绝添加新成员了哦?
    Bison:@EasyNzw 手机QQ 加即可
  • Waisti:好👏
  • e761838f3176:楼主,我需要 你的帮助!!!这个demo有吗!!万分感谢!!有偿也可以!!!
    e761838f3176:@Bison 楼主,我现在是在用swift3.0,想写一个跟你一样的这个界面,上面一部分该怎么写。。。我是新手,刚接触swift。。能拜师吗!!!!
    Bison:@e761838f3176 swift3.0和这个不一样的 代码已经都贴这了,demo 没保存
  • 歌的神:用KVC比较麻烦,你这样请求的比较简单,受用了 :blush:
  • dd1d1568f067:你的字典转模型一般都是手写的么?
    Bison:@一风吹记忆 KVC 第三方 runtime自己写都可以,写个文章只为通俗易懂 :smile:
  • d7696d1e9384:这里的 width 和 height是怎么赋值的,collectionView 的 宽 高
    Bison:@455483293 宽是根据比例设置的,高写死的
  • 91af9dda6970:整的真好
    Bison:@王好人 :confetti_ball:多谢赞赏:smile:
  • 6aae6f0aedb6:可否有源代码下载?headview和goodmodel都不懂
    Bison:@SimonLu heeadview主要是写了些UI,model主要写了数据解析,demo没有留哦,😅
  • brance:有demo吗,大神,最近在学九宫格。
    Bison:@Brance 九宫格的找到关键的代码就可以了,我这边没保留demo
  • e7ae4f56976a:你好,可以转载吗
    e7ae4f56976a:@Bison 好的 会附链接的
    Bison:@布_Rhett 可以,加上所有的超链接
  • MonsterNanny:好奇博客是咋弄的啊, 求学啊
    MonsterNanny:@Bison 好的...谢谢 :+1:
    Bison:@Whoateme github博客可以百度下
  • ff00a5b2fed8:刚好最近学swift、非常不错

本文标题:Swift纯代码走进UICollectionView

本文链接:https://www.haomeiwen.com/subject/negbcttx.html