我找到了一个解决方案,使用
custom(layoutSize: NSCollectionLayoutSize, itemProvider: @escaping NSCollectionLayoutGroupCustomItemProvider)
我创建了以下扩展,它计算组中每个元素的框架,将适合每行的尽可能多的项目居中
extension NSCollectionLayoutGroup {
static func verticallyCentered(cellSizes: [CGSize], interItemSpacing: CGFloat = 10, interRowSpacing: CGFloat = 10) -> NSCollectionLayoutGroup {
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(100))
return custom(layoutSize: groupSize) { environment in
var items: [NSCollectionLayoutGroupCustomItem] = []
var yPos: CGFloat = environment.container.contentInsets.top
var rowSizes: [CGSize] = []
func totalWidth() -> CGFloat {
rowSizes.map(\.width).reduce(0) {
$0 == 0 ? $1 : $0 + interItemSpacing + $1
}
}
func addRowItems() {
var xPos = (environment.container.effectiveContentSize.width - totalWidth())/2 + environment.container.contentInsets.leading
let maxItemHeight = rowSizes.map(\.height).max() ?? 0
let rowItems: [NSCollectionLayoutGroupCustomItem] = rowSizes.map {
let rect = CGRect(origin: CGPoint(x: xPos, y: yPos + (maxItemHeight - $0.height) / 2), size: $0)
xPos += ($0.width + interItemSpacing)
return NSCollectionLayoutGroupCustomItem(frame: rect)
}
items.append(contentsOf: rowItems)
}
for (index, cellSize) in cellSizes.enumerated() {
rowSizes.append(cellSize)
if totalWidth() > environment.container.effectiveContentSize.width {
rowSizes.removeLast()
addRowItems()
yPos += (cellSize.height + interRowSpacing)
rowSizes = [cellSize]
}
if index == cellSizes.count - 1 {
addRowItems()
}
}
return items
}
}
}
然后创建一个包含该部分中所有项目的单个组的布局部分。首先,您首先需要计算该部分中所有元素的大小,然后将它们传递给上面的函数,就像这样(注意我在这里使用的是 DiffableDataSource)……</p>
func someLayoutSection(sectionIndex: Int) -> NSCollectionLayoutSection {
let itemCount = collectionView.numberOfItems(inSection: sectionIndex)
let cell = SomeCell(frame: .zero)
let cellSizes: [CGSize] = (0..<itemCount).compactMap {
switch diffableDataSource.itemIdentifier(for: IndexPath(item: $0, section: sectionIndex)) {
case let .someItem(something):
cell.configure(thing: something)
return cell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
default:
return nil
}
}
let group = NSCollectionLayoutGroup.verticallyCentered(cellSizes: cellSizes)
group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20).scaled
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: 20, leading: 0, bottom: 20, trailing: 0)
return section
}
然后创建布局……</p>
func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [unowned self] sectionIndex, environment in
let section = diffableDataSource.snapshot().sectionIdentifiers[sectionIndex]
switch section {
case .someSection:
return someLayoutSection(sectionIndex: sectionIndex)
case .otherSection:
// etc
}
}