TLDR; Depending on the section, I need the cells to be sized either:
Here is a pictogram of what we need to clear any ambiguity that might exists.
I am looking for simply: "Yes, you can achieve this with compositional layout and here is how...". Or "No, you cannot implement this with compositional, you must use flow layout or some other custom layout."
Couple of additional requirements:
UITableViewAutomaticDimension
Background info:
You can build the "section 2" layout using UICollectionViewCompositionalLayout
. Here's how:
let layoutSize = NSCollectionLayoutSize(
widthDimension: .estimated(100),
heightDimension: .absolute(32)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: .init(
widthDimension: .fractionalWidth(1.0),
heightDimension: layoutSize.heightDimension
),
subitems: [.init(layoutSize: layoutSize)]
)
group.interItemSpacing = .fixed(8)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16)
section.interGroupSpacing = 8
return .init(section: section)
The important part is that the group takes up the available width using .fractionalWidth(1.0)
, but the subitems have an estimated width. Just make sure your collection view cell can be self-sized by overriding sizeThatFits(_:)
, preferredLayoutAttributesFitting(_:)
or using Auto Layout. The result will be a layout that looks like this:
To use "section 1" and "section 2" in the same UICollectionViewCompositionalLayout
, just create your layout using init(sectionProvider:)
, where you return the appropriate NSCollectionLayoutSection
for the current section identifier:
func createCollectionViewLayout() -> UICollectionViewCompositionalLayout {
.init(sectionProvider: { [weak self] sectionIndex, _ in
guard let sectionIdentifier = self?.dataSource.snapshot().sectionIdentifiers[sectionIndex] else { return nil }
switch sectionIdentifier {
case .section1: return self?.createSection1()
case .section2: return self?.createSection2()
}
})
}
It's worth noting you may see some odd behavior with this layout if your view controller is presented using the default pageSheet
style on iOS 13+. I have a related question about that here (using a slightly different layout).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With