I use my own layout for UICollectionView. My cell should have a fixed width and flexible height.
The cell consists of UImageViewand a UIStackView. The limitations are UIImageViewas follows:
image.top = cell.top
image.width = cell.width
image.height = image.width * 1.33
image.centerX = cell.centerX
image.bottom = stackView.top
The view of the stack is similar, and it is really attached to the bottom of the cell.
When the system calls preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
I do some calculations to get cell height.
let preferredAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
let size = CGSize(width: layoutAttributes.frame.width,
height: UILayoutFittingCompressedSize.height)
let preferredSize = systemLayoutSizeFitting(size,
withHorizontalFittingPriority: .defaultHigh,
verticalFittingPriority: .fittingSizeLevel)
It turns out that the preferred size is calculated using the size of the imageView object, and not subject to restrictions. So for an image with 850x850 (and a cell with 160 width points) I get a much higher height than I expect, and therefore a cell with huge bottom space.
-, .
, , , layoutAttributes setNeedsLayout() layoutIfNeeded(), . , , , .
?
.