具体代码如下:
1、声明
var hCollectionView:UICollectionView?
var layout:UICollectionViewFlowLayout? let courser = [
["name":"jack chen","pic":"1.jpeg"],
["name":"jack chen","pic":"1.jpeg"],
["name":"jack chen","pic":"1.jpeg"],
["name":"jack chen","pic":"1.jpeg"],
["name":"jack chen","pic":"1.jpeg"]
]
2、创建流布局,并初始化cellevtionView
// 设置布局流格式
layout = UICollectionViewFlowLayout()
layout?.itemSize = CGSize(width:self.view.frame.width/-,height:)
// 列间距,行间距,偏移
layout?.minimumInteritemSpacing = //列间距
layout?.minimumLineSpacing = //行间距
// layout?.sectionInset = UIEdgeInsets(top:5,left:0,bottom:0,right:0) self.hCollectionView = UICollectionView.init(frame: CGRect(x:,y:,width:kScreenWidth,height:kScreenHeight), collectionViewLayout: layout!)
self.hCollectionView?.delegate = self
self.hCollectionView?.dataSource = self
self.hCollectionView?.register(UINib.init(nibName: "hCell", bundle: nil), forCellWithReuseIdentifier: "hCell")
self.hCollectionView?.backgroundColor = UIColor.orange
//collectionview的偏移量
// self.hCollectionView?.contentInset = UIEdgeInsets(top:5,left:0,bottom:5,right:0) self.view.addSubview(self.hCollectionView!)
3、代理方法的实现
// 行数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return courser.count
} // 获取单元格
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:hCell = self.hCollectionView?.dequeueReusableCell(withReuseIdentifier: "hCell", for: indexPath) as! hCell
//这里判断了下奇偶数
if indexPath.item% == {
cell.backgroundColor = UIColor.red
cell.bgImg.image = UIImage(named:self.courser[indexPath.item]["pic"]!)
cell.descLab.text = self.courser[indexPath.item]["name"] }else{
cell.backgroundColor = UIColor.yellow
cell.bgImg.image = UIImage(named:self.courser[indexPath.item]["pic"]!)
cell.descLab.text = self.courser[indexPath.item]["name"]
}
最终效果图:
上面这种的话,是标准的流布局,设定好item的尺寸,会随着屏幕向下平铺,但是还有一种自定义的流布局,例如一些门户类app的首页,左边有一个大的Item,右边是2个小的item,两个小的总高度和一个大的Item的高度是一致的!其实就是几个方法,东西不难,敲几遍都差不多了,这里仅做记录!
实现自定义流布局的话,主要是实现这3个方法:
// 内容区域总大小,不是可见区域
override var collectionViewContentSize: CGSize
// 所有单元格位置属性
override func layoutAttributesForElements(in rect: CGRect)
-> [UICollectionViewLayoutAttributes]?
// 这个方法返回每个单元格的位置和大小
override func layoutAttributesForItem(at indexPath: IndexPath)
-> UICollectionViewLayoutAttributes?