I want the cell to horizontaly Hug its content
我UICollectionViewCompositionalLayout
在水平模式下使用widthDimension: .estimated(100)
,应该用它来计算内容大小
但是单元格/组的宽度根本不是由内容大小计算的 ,而是设置为估计值,因为它是一个绝对值
即使向标签添加宽度约束也不会影响单元格大小
这是预期的行为吗?如果是,那为什么?以及如何获得预期的结果?
class LabelCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
class ViewController: UIViewController, UICollectionViewDataSource {
func buildLayout() -> UICollectionViewCompositionalLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(100), heightDimension: .absolute(32))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .estimated(100), heightDimension: .absolute(32))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 10
let configuration = UICollectionViewCompositionalLayoutConfiguration()
configuration.scrollDirection = .horizontal
return UICollectionViewCompositionalLayout(section: section, configuration: configuration)
}
@IBOutlet weak var collectionView: UICollectionView!
let items = ["1", "12", "12345", "123456789"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.collectionViewLayout = buildLayout()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell", for: indexPath) as! LabelCell
c.label.text = items[indexPath.row]
return c
}
}