在垂直堆栈视图中具有自动项目大小的水平分页 UICollectionView? [英] Horizontal paging UICollectionView with automatic item size in a vertical stack view?
问题描述
我有一个主要的垂直堆栈视图(第 1 帧),它有一个带有流布局的水平分页集合视图 (CollectionView),它有几个单元格 (Cell).每个单元格都带有几个标签(标题、描述)的垂直堆栈视图.
I have a main vertical stack view (Frame 1), that has a horizontal paging collection view with flow layout (CollectionView), which has a couple of cells (Cell). Each cell comes with a vertical stack view of a couple of labels (Title, Description).
有没有办法让最高的单元格决定集合视图的高度,而主堆栈视图的宽度决定单元格的宽度?
Is there a way to let the tallest cell determine the collection view's height, while the main stack view width determines the width of the cells?
默认情况下,当我使用 layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
时,集合视图不可见(似乎它不会继承"单元格的高度).
By default, the collection view is not visible when I use layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
(seemingly it does not "inherit" the cells' height).
目前,我通过为集合视图设置固定高度来解决这个问题,并在 collectionView(_:layout:sizeForItemAt:)
collectionView(_:layout:sizeForItemAt:) 中手动定义了项目大小代码>(并且单元格是灵活的).
For now, I worked around the issue by setting a fixed height for the collection view, and defined the item size manually in the collectionView(_:layout:sizeForItemAt:)
(and the cells are flexible).
推荐答案
由于 CollectionViews(和 TableViews)没有 intrinsicContentSize
,布局引擎无法知道正确的大小您的收藏没有适当的限制.需要一个子类来提供此属性.
Since CollectionViews (and TableViews) don't have an intrinsicContentSize
, there is no way for the layout engine to know the correct size of your collection without the appropriate constraints. A subclass is needed to provide this property.
在您的子类中:
override var intrinsicContentSize: CGSize {
return CGSize(self.contentSize.height, self.superview!.bounds.width)
}
另外,不要忘记在重新加载数据时使您的内容大小无效:
Also, don't forget to invalidate your content size when reloading data:
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
有关内在内容大小的更详细说明,请查看 Apple 的文档
For a more detailed explanation on intrinsicContentSize check Apple's Documentation
这篇关于在垂直堆栈视图中具有自动项目大小的水平分页 UICollectionView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!