无故事王国
2023-11-01 b3269976c84d03208f633cd0136a6f78e8dd53f7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
//  WaterFallFlowLayout.swift
//  WanPai
//
//  Created by 杨锴 on 2023/6/8.
//
 
import UIKit
 
protocol WaterFallLayoutDelegate: NSObjectProtocol {
    func waterFlowLayout(_ waterFlowLayout: WaterFallFlowLayout, itemHeight indexPath: IndexPath) -> CGFloat
}
 
@available(*,deprecated,message: "废弃")
class WaterFallFlowLayout: UICollectionViewFlowLayout {
 
    weak var delegate: WaterFallLayoutDelegate?
    // 列数
    var cols = 4
    var itemCount:Int = 0
    // 布局数组
    var layoutAttributeArray: [UICollectionViewLayoutAttributes] = []
    // 高度数组
    fileprivate lazy var yArray: [CGFloat] = Array(repeating: self.sectionInset.top, count: cols)
    
    fileprivate var maxHeight: CGFloat = 0
    
    override func prepare() {
        super.prepare()
        // 计算每个 Cell 的宽度
        let itemWidth = (collectionView!.bounds.width - sectionInset.left - sectionInset.right - minimumInteritemSpacing * CGFloat(cols - 1)) / CGFloat(cols)
        // Cell 数量
//        let itemCount = collectionView!.numberOfItems(inSection: 0)
        // 最小高度索引
        var minHeightIndex = 0
        // 遍历 item 计算并缓存属性
        for i in layoutAttributeArray.count ..< itemCount {
            let indexPath = IndexPath(item: i, section: 0)
            let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            // 获取动态高度
            let itemHeight = delegate?.waterFlowLayout(self, itemHeight: indexPath)
            
            // 找到高度最短的那一列
            let value = yArray.min()
            // 获取数组索引
            minHeightIndex = yArray.firstIndex(of: value!)!
            // 获取该列的 Y 坐标
            var itemY = yArray[minHeightIndex]
            // 判断是否是第一行,如果换行需要加上行间距
            if i >= cols {
                itemY += minimumInteritemSpacing
            }
            
            // 计算该索引的 X 坐标
            let itemX = sectionInset.left + (itemWidth + minimumInteritemSpacing) * CGFloat(minHeightIndex)
            // 赋值新的位置信息
            attr.frame = CGRect(x: itemX, y: itemY, width: itemWidth, height: CGFloat(itemHeight!))
            // 缓存布局属性
            layoutAttributeArray.append(attr)
            // 更新最短高度列的数据
            yArray[minHeightIndex] = attr.frame.maxY
        }
        maxHeight = yArray.max()! + sectionInset.bottom
        
    }
}
 
extension WaterFallFlowLayout {
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // 返回相交的区域
        return layoutAttributeArray.filter {
            $0.frame.intersects(rect)
        }
    }
    
    override var collectionViewContentSize: CGSize {
        return CGSize(width: collectionView!.bounds.width, height: maxHeight)
    }
}