组合布局中集合视图自调整单元格大小问题
我正在使用集合视图组合布局来显示带有两个标签的单元格,这些标签的高度可以根据标签的内容而增长。单元格中的其他所有内容都是固定的。
我制作了这样的部分:
let item = NSCollectionLayoutItem(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .estimated(300)),
subitems: [item])
let section = NSCollectionLayoutSection(group: group)
问题是,它要么太大,要么太小,但永远不会计算出正确的高度。 我的假设是,这是因为我在 configure
方法中设置标签的文本,而不是在单元初始化期间设置。
let cell = collectionView.dequeueReusableCell(
reusableCell: MyCustomCell.self,
indexPath: indexPath)
cell.configure(viewModel: viewModel)
我有什么想法可以解决它吗?我尝试使布局无效或重新加载数据以重新计算高度,但没有帮助。
I am using a collection view compositional layout to display a cell with two labels that can grow in height, depending on the content of the labels. Everything else in the cell is fixed.
I make a section like this:
let item = NSCollectionLayoutItem(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .estimated(300)),
subitems: [item])
let section = NSCollectionLayoutSection(group: group)
The problem is, it's either too big, or too small, but the correct height is never being calculated.
My assumption is that this is due to the fact that I am setting the text for the label inside a configure
method but not during the cell initialization.
let cell = collectionView.dequeueReusableCell(
reusableCell: MyCustomCell.self,
indexPath: indexPath)
cell.configure(viewModel: viewModel)
Any ideas how I can fix it? I tried invalidating the layout or reloading the data to re-calculate the height, but it didn't help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于标签位于商品上,并且商品是决定组大小的商品,因此您的商品需要有一个
.estimated
高度尺寸,如果您只计划每组包含一个商品,则该组的高度尺寸将与该项目的高度尺寸相同。因此,在这种情况下,项目和组都应该具有.estimated(300)
。您当前的代码基本上是说:使项目与我们估计为 300pt 高的组一样高,但随后该组无法知道它的高度,因此您最终会得到错误的布局。通常,您只想对嵌套在具有绝对或分数尺寸(沿给定轴)的组中的项目使用分数尺寸以避免这种情况。Since the labels live on the item and the item is the one that sizes the group, you need to have an
.estimated
height dimension on your item and if you only plan on having one item per group then the heigh dimension of the group would be the same as the item. So in this case both the item and the group should have.estimated(300)
. Your current code is basically saying: Make the item as tall as the group which we estimate is 300pt tall but then the group has no way to know it's height and thus you end up with the wrong layout. Generally you want to only use fractional dimensions for items nested in groups with absolute or fractional dimensions (along a given axis) to avoid this.