0

我有一个使用组合布局的 collectionView。集合视图有一个标题,标题内部是一个标签,根据从 API 加载的数据,它可以有不同的高度。

我正在以编程方式做所有事情。

我已经使用以下布局设置了 collectionView

private func setUpLayout() -> NSCollectionLayoutSection {
    let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)))
    item.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)
    
    let groupHeight = (120 * 5) / 7 // 7:5 aspect ratio from a fixed width
    let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(CGFloat(groupHeight + 16))), subitem: item, count: 1)
    
    let section = NSCollectionLayoutSection(group: group)
    
    section.boundarySupplementaryItems = [
        NSCollectionLayoutBoundarySupplementaryItem(
            layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(0.6)),
            elementKind: UICollectionView.elementKindSectionHeader,
            alignment: .top)
    ]
    
    return section
}

如何将标题的高度设置为取决于其内容的高度?

我尝试了 collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize 但这似乎不适用于组合布局。

4

0 回答 0