How to center align cells in UICollectionViewCompositionalLayout
In UICollectionViewCompositionalLayout
, we can control the width of cells by specifying the layout sizes for NSCollectionLayoutItem
and NSCollectionLayoutGroup
.
The Problem
However, setting width to a smaller (than 1) fraction value will just left align the cells. For example, in the code below at (1), we set groupSize
widthDimension
to .fractionalWidth(0.5)
, which means it will span half of the width of UICollectionView
it is in.
This results in half container width cells, but they are all left aligned. 😅
You may think there should be a some dedicated “alignment” property for this, right? Sadly, there isn’t. So how do we center align it?
The Solution
In NSCollectionLayoutEnvironment
, there is a container.contentSize
property which represents “The size of the…