6

我已经成功地能够使用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

4

1 回答 1

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 条)。

于 2020-09-28T21:51:36.903 回答