UICollectionViewCompositionalLayout 具有自调整大小的单元格

Nic*_*ese 4 collectionview swift ios13

我有一个用于标签视图的基本组合布局。单元格只包含一个带有自动布局约束的标签。目标是在垂直和水平方向自动调整单元格大小以适合标签。对于组合布局,当我分别将 NSCollectionLayoutGroup 设置为垂直或水平时,我只能获得估计的宽度或高度。我无法让它对两个轴都起作用。我缺少什么吗?它应该是这样的:

在此处输入图片说明

let layout = UICollectionViewCompositionalLayout { (section: Int, environment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in

        let layoutSize = NSCollectionLayoutSize(widthDimension: .estimated(100), heightDimension: .estimated(40))

        let item = NSCollectionLayoutItem(layoutSize: layoutSize)

        let group = NSCollectionLayoutGroup.vertical(layoutSize: layoutSize, subitem: item, count: 1)

        let section = NSCollectionLayoutSection(group: group)
        section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20)
        section.interGroupSpacing = 10
        section.orthogonalScrollingBehavior = .groupPaging

        return section
    }
Run Code Online (Sandbox Code Playgroud)

Tho*_*enA 6

不确定我是否正确理解您的问题,但这是您如何实现以下标签视图。

多行标签视图

  private func createLayout() -> UICollectionViewLayout {

        let estimatedHeight: CGFloat = 50
        let estimatedWidth: CGFloat = 100

        let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(estimatedWidth),
                                              heightDimension: .estimated(estimatedHeight))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        item.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: nil, top: .fixed(4), trailing: .fixed(8), bottom: .fixed(4))

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                               heightDimension: .estimated(estimatedHeight))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
                                                       subitems: [item])

        let section = NSCollectionLayoutSection(group: group)

        let layout = UICollectionViewCompositionalLayout(section: section)
        return layout
    }
Run Code Online (Sandbox Code Playgroud)