主要步骤:添加一个class继承UICollectionViewFlowLayout
- 添加一个itemCount:Int,用来设置item数量,在创建对象时要传入
- 添加一个数组属性,用来存放每个item的局部信息(item.frame)
- 重写prepare方法,设置每个item的frame,并存入数组
- 重写layoutAttributesForElements方法,并将存放item.frame信息的数组返回
//
// UICollectionViewFlowLayout1.swift
// snapkit-study
//
// Created by YY on 2021/1/19.
//
import UIKit
class WaterFallLayout: UICollectionViewFlowLayout {
// 封装一个属性,用来设置item的个数
let itemCount:Int
// 添加一个数组属性,用来存放每个item的布局信息
var attributeArray:Array<UICollectionViewLayoutAttributes>?
// 实现必要的构造方法
required init?(coder aDecoder: NSCoder) {
itemCount = 0
super.init(coder:aDecoder)
}
// 自定义一个初始化构造方法
init(itemCount:Int) {
self.itemCount = itemCount
super.init()
}
override func prepare() {
//调用父类的准备方法
super.prepare()
//设置为竖直布局
self.scrollDirection = .vertical
//初始化数组
attributeArray = Array<UICollectionViewLayoutAttributes>()
//先计算每个item的宽度,设置为三列布局
let WIDTH = (UIScreen.main.bounds.size.width-2 * self.minimumInteritemSpacing)/3
//定义一个元组表示每一列的动态高度(决定有多少列)
var queueHieght:(one:Int,two:Int, thrid:Int) = (0, 0, 0)
//进行循环设置item的frame
for index in