I'm using UICollectionViewCompositionalLayout to create a vertically scrolling list of horizontally scrolling (orthogonally scrolling) lists in my iOS app.
When I specify an estimated height for both the item and the group, the collection view adjusts its height when taller items scroll into view.
If on the other hand, I specify an estimated height for the group and a fractional height of 1.0 for the item, the height seems to be treated as an absolute value, regardless of constraints and compression resistance that are set.
Here's my createSection function:
func createSection(sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(
widthDimension: .absolute(90),
heightDimension: .estimated(44)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(90 / layoutEnvironment.container.effectiveContentSize.width),
heightDimension: .estimated(44)
)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 16.0
section.orthogonalScrollingBehavior = .continuous
return section
}
I tried subclassing UICollectionViewCompositionalLayout
and overriding layoutAttributesForElementsInRect
to adjust attributes based on the tallest item in each section. This resulted in flickering during scrolling, however, which I suspect is due to prepare
being called continuously on bounds change.
I don't know the height of the view in each cell in advance. However, I've ensured that they are correctly constrained and that compression resistance is set to required on the vertical axis.
Expected Behaviour: The height of each cell to be dynamically adjusted based on its content, without causing layout changes or flickering when cells of different heights come into view.
Actual Behavior: Specifying estimated height for both item and group causes layout changes upon scrolling, while setting fractional height for the item results in the group's estimated height being treated as an absolute value. Overriding layoutAttributesForElementsInRect and adjusting there causes flickering.
How can I handle dynamic cell heights in UICollectionViewCompositionalLayout without causing these layout issues? I would greatly appreciate any advice or potential solutions.
Here's a Swift Playground demonstrating the problem: https://github.com/aodhol/CompositionalProblem/tree/main
Screenshots showing estimated sizes too large and too small: