Collection View 大部分思想与 Table View 一样,核心就是可以实现比 Table View 更复杂的布局,更灵活。
import UIKit
import Foundation
// 实现两个协议
class ViewController:UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
// 假设 cell 高度
let collentionCellHeight:CGFloat =110
// 屏幕宽度:
let width =UIScreen.main.bounds.width
var collection:UICollectionView!
//数据源
var dataArr= [“1”,“23”,“4”,“21”,“2”,“32”,“5646”,“3234”,“435”,“242”]
overridefunc viewDidLoad() {
super.viewDidLoad()
view.backgroundColor =UIColor.white
initCollection()
}
func initCollection(){
// 与 tableView 不同 一:必有 layout
let lay =UICollectionViewFlowLayout()
// 每个元素大小:
lay.itemSize =CGSize(width:width/3, height:collentionCellHeight)
(一会有定义不同cell不同高度)
lay.minimumInteritemSpacing =20 //行间距
// 构造collectionView
// collection
collection =UICollectionView(frame:view.bounds,collectionViewLayout: lay)
// 俩协议的代理
collection.delegate =self
collection.dataSource =self
collection.backgroundColor = .white
// 注册cell,和tableView一样
// 用collectionView时候,cell都是自定义的,自定义的ELCollectionViewCell类在最下面。现在先直接写
collection.register(ELCollectionViewCell.self,forCellWithReuseIdentifier:“cellID”)
view.addSubview(collection)
}
}
// collectionView的代理方法,和tableView差不多
1.返回行数
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int {
returndataArr.count
}
2. cell内容
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) ->UICollectionViewCell {
let cell:ELCollectionViewCell =collection.dequeueReusableCell(withReuseIdentifier:“cellID”, for: indexPath)as? ELCollectionViewCell
let model =dataArr[indexPath.item]
cell.labelName?.text = “name:” + model
cell.labelNum?.text =model
return cell
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) {
//业务需求点击实现的东西自定
}
还有一个协议,是定义详细布局的,每个cell的高度之类的,叫 UICollectionViewDelegateFlowLayout,里面的方法看名字就可以知道作用了;如果要实现更复杂的布局,就要自己实现一个 layout 类,一般用不到。
}
class ELCollectionViewCell: UICollectionViewCell {
let width =UIScreen.main.bounds.width
var labelName:UILabel?
var labelNum:UILabel?
overrideinit(frame:CGRect) {
super.init(frame: frame)
backgroundColor =UIColor.lightgray
// 加点外观
layer.cornerRadius =15
layer.borderWidth =0.3
layer.borderColor =UIColor.green.cgColor
labelName =UILabel(frame:CGRect(x:20, y:10, width:100, height:50))
labelNum =UILabel(frame:CGRect(x:20, y: 60, width:100, height:50))
labelName?.font =UIFont.boldSystemFont(ofSize:23)
labelNum?.font =UIFont.systemFont(ofSize:12)
labelName?.textAlignment = .center
labelNum?.textAlignment = .center
addSubview(labelName!)
addSubview(labelNum!)
}
requiredinit?(coder aDecoder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}