Swift4.0 UICollctionView纯代码

最近进行Swfit4.0的学习 只感觉坑太深 慢慢爬 


计算器的代码就不上了



嗯,创建个CollectionView不多说 上代码

func createCollectionView(){

let layout = UICollectionViewFlowLayout.init()

let cellWidth = view.bounds.width/7

layout.itemSize = CGSize.init(width:cellWidth,height:cellWidth+20)

layout.minimumLineSpacing = cellWidth/2

layout.minimumInteritemSpacing = cellWidth/2

layout.sectionInset = UIEdgeInsets.init(top: cellWidth/2-16, left: cellWidth/2, bottom: 70, right: cellWidth/2)

CV = UICollectionView.init(frame: CGRect(x:0,y:64,width:view.bounds.width,height:view.bounds.height/2),collectionViewLayout: layout)

CV.delegate = self

CV.dataSource = self

CV.backgroundColor = .white

view.addSubview(CV)

CV.register(Add_Cell.self, forCellWithReuseIdentifier: "cell")

}

扩展VC

extension ParticularViewController:UICollectionViewDelegate,UICollectionViewDataSource {

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return self.array.count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = CV.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Add_Cell

let dict = self.array[indexPath.item] as! CategoryModel

cell.typeImgView.image = UIImage.init(named:dict.typeImg)

cell.typeLabel.text = dict.typeName

return cell

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let dict = self.array[indexPath.item] as! CategoryModel

keyboardView.typeLabel.text = dict.typeName

nameStr = dict.typeName! as NSString

imgStr = dict.typeImg! as NSString

isIncome = dict.isIncome

}

}

Add_Cell继承自UICollectionViewCell

class Add_Cell: UICollectionViewCell {

let width = UIScreen.main.bounds.size.width/7

var typeImgView:UIImageView!

var typeLabel:UILabel!

override init(frame: CGRect) {

super.init(frame: frame)

typeImgView = UIImageView(frame:CGRect(x:width/2-15,y:width/2-15,width:30,height:30))

self.addSubview(typeImgView!)

typeLabel = UILabel(frame:CGRect(x:0,y:width,width:width,height:20))

typeLabel.textAlignment = NSTextAlignment.center

self.addSubview(typeLabel!)

}

required init(coder aDecoder: NSCoder) {

fatalError("init(coder:) has not been implemented")

}

}

你可能感兴趣的:(Swift4.0 UICollctionView纯代码)