效果图如下:
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>
网友评论