简体   繁体   中英

Horizontal paging UICollectionView with automatic item size in a vertical stack view?

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?


By default, the collection view is not visible when I use layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize (seemingly it does not "inherit" the cells' height).

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).

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.

In your subclass:


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()
}

For a more detailed explanation on intrinsicContentSize check Apple's Documentation

As the content is static, I think simply using UIScrollView is a pretty viable alternative here (as the dynamic nature of the collection view is not a requirement). The collection view could be a stack embedded into a scroll view, then the contains between the dimensions can be simply set upon initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM