How to center align cells in UICollectionViewCompositionalLayout

Thongchai Kolyutsakul
SwiftBlade
Published in
3 min readApr 26, 2022

--

Center aligned, half container width cells. Our goal :)

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…

--

--

Thongchai Kolyutsakul
SwiftBlade

iOS developer since 2009. Working @Viki in Singapore. I write about iOS development, Swift language, and general software engineers tips.