Free-Thinker

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 = "

分类:

技术点:

相关文章: