UICollectionViewCompositionalLayout contentInsets with estimated values for its dimensions

307 Views Asked by At

Q: How do you apply contentInsets to a group whenever you use UICollectionViewCompositionalLayout where the axis uses estimated values for its dimension?

I have a simple app where I fetch some online data and then display the data to the user in a UICollectionViewCompositionalLayout.

The layout is using estimated values for the height dimensions (because I don't know the sizes until the data has loaded) and I want to set contentInsets on the group.

let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(100))
let item = NSCollectionLayoutItem(layoutSize: itemSize)

let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(100))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])

// Set content insets on the group, which is not allowed for estimated dimensions.
group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)

let section = NSCollectionLayoutSection(group: group)
let layout = UICollectionViewCompositionalLayout(section: section)

collectionView.collectionViewLayout = layout

The problem I'm facing is that setting contentInsets on the group is not allowed according to the documentation whenever you use estimated dimensions (and Xcode also gives a warning in the console):

The value of this property is ignored for any axis that uses an estimated value for its dimension. For more information, see estimated(_:)

https://developer.apple.com/documentation/uikit/nscollectionlayoutitem/3199084-contentinsets

Things I've considered:

1: My only "solution" is to update my constraints in my cells to include these insets but I'd rather want to fix these insets on a higher level of abstraction (the UICollectionView that is).

2: Is it an option to assign a new layout to the collectionView without estimated values once the data has loaded? Would this come with performance issues?

3: This SO comment also mentions using contentInsets is not possible with estimated values: https://stackoverflow.com/a/58568964/9339888, however no solution has been provided here.

0

There are 0 best solutions below