wallpaperAI/wallpaper_BProject/Tool/WaterfallFlowLayout.swift
2024-09-03 09:42:18 +08:00

103 lines
3.4 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// 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..<numberOfColumns {
xOffset.append(CGFloat(column) * columnWidth)
}
// Y
var column = 0
var yOffset: [CGFloat] = .init(repeating: 0, count: numberOfColumns)
// items
for item in 0..<collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
//
// let photoHeight = CGFloat(arc4random_uniform(100) + 150)
// let
let height = cellPadding * 2 + CGFloat(getRandomheight() ?? 150)
// X Y frame
let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
//
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
// Y
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] = yOffset[column] + height
//
column = column < (numberOfColumns - 1) ? (column + 1) : 0
}
}
//
override func layoutAttributesForElements(in rect: CGRect) -> [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)
}