如何使用UICollectionViewCompositionalLayout创建具有相等行高的网格布局

时间:2020-05-11 16:17:32

标签: ios swift uicollectionview grid uicollectionviewcompositionallayout

我已经能够成功使用UICollectionViewCompositionalLayout创建网格布局。但是,我无法找到一种聪明的方法来确保网格中每行中的UICollectionViewCell的高度是动态的时,它们的高度相同。也就是说,我希望单元格拉伸以填充行中高度方向上的可用空间。

所需的布局:

  • 网格(3 x N)
  • 可变高度单元格
  • 每个单元格在给定行中具有相同的高度。 (连续使用最大单元格高度)
  • 每个单元格底部的小分隔线。
+------+--+------+--+------+
|~~~~~~|  |~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|  |      |
|~~~~~~|  |      |  |      |
--------  -------   --------   <--- divider
+------+--+------+--+------+

注意:该行本身是正确的高度,但是我希望单元格内容能够扩展以填充可用空间,因为我需要在每个单元格的底部插入一个小的“行分隔符”。我曾考虑为此使用补充视图,但这似乎有些混乱。

当前尝试:

func createLayout() -> UICollectionViewLayout {
    let estimatedHeight: CGFloat = 100

    let item = NSCollectionLayoutItem(
        layoutSize: .init(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(estimatedHeight)),
        supplementaryItems: []
    )

    let groupLayoutSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                                 heightDimension: .estimated(estimatedHeight))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupLayoutSize, subitem: item, count: 3)


    let section = NSCollectionLayoutSection(group: group)
    section.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)
    section.interGroupSpacing = 10
    let layout = UICollectionViewCompositionalLayout(section: section)
    return layout
}

结果:

+------+--+------+--+------+
|~~~~~~|  |~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|  --------
|~~~~~~|  --------  
--------    
+------+--+------+--+------+

示例代码:https://github.com/johnliedtke/grid-layout

1 个答案:

答案 0 :(得分:1)

NSCollectionLayoutSupplementaryItem子类化NSCollectionLayoutItem,因此您应该能够将其添加为组的子项。所以你会用

let item = NSCollectionLayoutItem(
        layoutSize: .init(widthDimension: .fractionalWidth(1.0), heightDimension: .fractional(1))
    )

let sup = NSCollectionLayoutSupplementaryItem(
            layoutSize: .init(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(2)),
            elementKind: "LineReusableView",
            containerAnchor: .init(edges: [.bottom])
        )
let threeItemGroup = NSCollectionLayoutGroup.horizontal(layoutSize: groupLayoutSize, subitem: item, count: 3)
let group = NSCollectionLayoutGroup.vertical(layoutSize: layoutGroupSize,subitems: [threeItemGroup,sup])

let section = NSCollectionLayoutSection(group: group)

这应该导致您每个组的底部只有一行,而不是您希望的三行,但是您应该能够更改设计补充视图时的外观(使其绘制3条不同的线,而不仅仅是1)。