How to create dynamic width cells for compositional layout collection view. Telegram-Drawing-Text-Editing, ep. 3
1 min readDec 4, 2022
During creation compositional layout we need to make sure that the place 1, and the place 2 have the same estimated dimension:
func createLayout() -> UICollectionViewLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: /*1*/.estimated(100), heightDimension: .fractionalHeight(1))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: /*2*/.estimated(100), heightDimension: .fractionalHeight(1))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .continuous
section.interGroupSpacing = 15
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
This is crucial, because if you provide estimated dimension only for an item or only for a group you’ll faced with an error that tells you this is impossible for collection view to setup layout. The same technique is applied to hight dimension.
And of course, if you have a custom cells, don’t forget to add all subviews to its contentView and setup proper constraints, if you have any problems with anything mentioned above, don’t hesitate to leave a comment bellow and ask.