// // WaterfallFlowLayout.swift // wallpaper_BProject // // Created by 忆海16 on 2024/8/29. // import Foundation import UIKit // 自定义瀑布流布局 class WaterfallFlowLayout: UICollectionViewFlowLayout { let heightInt = [300,320,310,280,290] // 瀑布流列数 var numberOfColumns: Int = 2 // 单元格的内边距 var cellPadding: CGFloat = 2 // 用于缓存所有计算过的布局属性 private var cache: [UICollectionViewLayoutAttributes] = [] // 用于记录内容的高度 private var contentHeight: CGFloat = 0 // 返回集合视图内容的总尺寸 override var collectionViewContentSize: CGSize { return CGSize(width: collectionView?.bounds.width ?? 0, height: contentHeight) } // 准备布局,每次布局无效时都会调用 override func prepare() { // 如果缓存为空,且有 collectionView 存在,则计算布局 guard cache.isEmpty, let collectionView = collectionView else { return } // 计算每列的宽度 let columnWidth = collectionView.bounds.width / CGFloat(numberOfColumns) // 初始化每列的 X 偏移量 var xOffset: [CGFloat] = [] for column in 0.. [UICollectionViewLayoutAttributes]? { return cache.filter { $0.frame.intersects(rect) } } // 返回指定项目的布局属性 override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return cache[indexPath.item] } func getRandomheight() -> Int? { return heightInt.randomElement() } } //let randomNumber = Int.random(in: 0...500) func getRandomInt() -> Int?{ return Int.random(in: 0...500) }