jsdw_ios/QuickLocation/UIKit/CollectionHFlowLayout.swift

71 lines
2.2 KiB
Swift

//
// CollectionHFlowLayout.swift
// dinoGo
//
// Created by osell on 2023/1/17.
// Copyright © 2023 dino. All rights reserved.
//
import UIKit
class CollectionHFlowLayout: UICollectionViewLayout {
var rows: Int = 5
var colums: Int = 2
var itemSize: CGSize = .zero
var hSpacing: CGFloat = 10
var vSpacing: CGFloat = 10
var sectionInset: UIEdgeInsets = .zero
var attributesArr: [UICollectionViewLayoutAttributes] = []
var contentWidth: CGFloat = 0
var page = 0
// MARK: - Lifecycle
override func prepare() {
super.prepare()
attributesArr = []
contentWidth = 0
page = 0
let pageTotal = rows * colums
guard let itemCount = collectionView?.numberOfItems(inSection: 0) else { return }
for index in 0..<itemCount {
let indexPath = IndexPath(item: index, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
page = index / pageTotal
var x = ((itemSize.width + hSpacing) * CGFloat((index % pageTotal % colums)) + sectionInset.left)
x = x + CGFloat(page) * UIScreen.main.bounds.size.width
let y = (itemSize.height + vSpacing) * CGFloat((index % pageTotal / colums)) + sectionInset.top
attributes.frame = CGRect(origin: CGPoint(x: x, y: y), size: itemSize)
attributesArr.append(attributes)
}
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
attributesArr[indexPath.item]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
attributesArr.compactMap {
if rect.contains($0.frame) {
return $0
}
return nil
}
}
override var collectionViewContentSize: CGSize {
var height = itemSize.height * CGFloat(rows)
height = height + CGFloat(rows - 1) * vSpacing + sectionInset.top + sectionInset.bottom
return CGSize(width: CGFloat(page + 1) * kScreenWidth, height: height)
}
}