Swift3.0 创建UICollectionView

效果图如下:


Simulator Screen Shot 2017年6月23日 下午3.56.36.png

请看如下代码,cell是使用xib创建的:
<pre>
class SecondViewController: UIViewController , UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

var collectionView:UICollectionView?
var dataArray = NSMutableArray()
var imageArray = NSMutableArray()


override func viewDidLoad() {
    super.viewDidLoad()
    self.dataArray = ["BIGBANG","G-DRAGON","TOP","DAESUNG","SEUNGRI","TAEYANG","MINO","BOBBY","B.I"]
    self.imageArray = ["bigbang","gd","top","daesung","seungri","taeyang","mino","bobby","bi"]

   createCCollectionView()

}
//创建collectionView
func createCCollectionView(){

    let flowLayout = UICollectionViewFlowLayout()
    collectionView = UICollectionView.init(frame:self.view.frame,collectionViewLayout:flowLayout)
    //item大小
    flowLayout.itemSize = CGSize(width:(self.view.frame.size.width/4),height:130)
    flowLayout.minimumLineSpacing = 0
    flowLayout.minimumInteritemSpacing = 0
    collectionView?.backgroundColor = UIColor.groupTableViewBackground
    collectionView?.delegate = self
    collectionView?.dataSource = self


    //注册cell
    collectionView!.register(UINib (nibName: "XIBCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "XIBCollectionViewCell")
    self.view.addSubview(collectionView!)


}

</pre>
下面是collectionView的代理方法:
<pre>
//分区item个数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataArray.count
}

//定义cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XIBCollectionViewCell", for: indexPath)as!XIBCollectionViewCell
    cell.cellImage?.image = UIImage(named:self.imageArray[indexPath.row] as! String)
    cell.cellLabel!.text = self.dataArray[indexPath.row] as? String
    return cell

}

</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容