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
}
}
要正确调整单元格大小,请更改:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1)
To this:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
我不确定为什么需要进行此更改,因为这些行似乎说的是同一件事。也就是说,只要您的集合视图单元格通过覆盖指定实际单元格大小,它就会起作用sizeThatFits(_:)
, preferredLayoutAttributesFitting(_:)
,使用自动布局等。
对于它的价值,第一个函数签名的文档说:
指定一个包含 N 个项目的组大小相等沿着水平轴。
第二个函数签名的注释没有对相同大小的项目做出这样的声明。它说:
指定一个组,该组将重复项目,直到可用的水平空间耗尽。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)