UICollectionView简单示例

首先建立一个Single View Application,而后在stroyboard已有的View Collection中拖入一个UICollectionView,大小本身调节。swift

而后按住option键并点击项目中的ViewController.swift文件,使窗口分屏。而后按住control键鼠标点击UICollectionView而后拖到ViewController中合适位置,命名为collectionView。markdown

这里写图片描述

ViewController实现UICollectionViewDelegate,UICollectionViewDataSource这两个协议。
这里写图片描述ide

在viewDidLoad方法中加入以下代码。编码

//设置代理与数据源
collectionView.delegate = self;
collectionView.dataSource = self;

接下来须要注册UICollectionViewCell类,使用默认的Cell,其中须要一个重用UICollectionViewCell的标识,因此为了方便起见在ViewController中添加一个变量,其中具体内容能够自定义。spa

var identifier = "collectionView"

在viewDidLoad中继续添加以下代码用来注册Cell代理

//注册cell类
        collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: identifier)

设置collectionView的尺寸,我这里设为与屏幕等宽同高code

//设置UICollectionViewCell的尺寸

collectionView.bounds = UIScreen.mainScreen().bounds

实现了UICollectionViewDataSource协议,就须要实现协议中的非option方法,能够直接去UICollectionViewDataSource里面复制这两个方法,能够看到这两个方法的原型。coffeescript

这里写图片描述

如今在ViewController中实现这两个方法图片

这里写图片描述

为了方便起见,这里分组的个数使用硬编码,返回10ip

//该方法用来返回分组中cell的个数,因为示例只有一个分组,因此只须要返回该分组中cell的个数便可
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

实现func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize方法

//该方法返回对应的cell
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

//利用重用获取cell
var cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! UICollectionViewCell

//在获取到的cell中添加一个自定义的UILabel
var label = UILabel(frame: CGRectMake(0, 0, 100, 100))
//用当前序号做为label内容
label.text = String(indexPath.item)
//切记,要把空间添加到cell的contentview下!
cell.contentView.addSubview(label)

//设置cell的背景色
cell.backgroundColor = UIColor.blueColor()

return cell


}

最后,若是须要设置一下cell的尺寸,须要ViewController实现UICollectionViewDelegateFlowLayout协议。而且实现sizeForItemAtIndexPath方法。

//该方法返回的CGSize为Cell的尺寸
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(100, 100)
    }

最终效果:
这里写图片描述

相关文章
相关标签/搜索