Modern Layout on UIKit with UICollectionView Compositional Layout

Enes Buğra Yenidünya
2 min readJul 14, 2022

At WWDC19, Apple introduced Compositional Layout for UICollectionView, along with Diffable Data Sources. This article demonstrates both.

Creating collection views for iOS apps were pretty straightforward. A simple UICollectionFlowLayout would create flowing lists or grids of items. But things got a lot harder when the layout got a little more complex. A horizontal list within a vertical collection view required some extra tricks that every experienced iOS developer has inevitably used. Hopefully, at WWDC19, Apple introduced UICollectionView Compositional Layout, along with Diffable Data Sources. Now we can create nested layouts via and creating these layouts are quite easy.

We are going to look at these two new APIs today. First, we are going to create UICollectionView Compositional Layout object and then we’ll to feed the UICollectionView using UICollectionViewDiffableDataSource.

UICollectionView Compositional Layout

When we are creating new UICollectionViewCompositionalLayout we need three things; Section, Group and Item. Section is same as before but here we have actually new two things here, Group and Item. Think Group as another UICollectionView that has multiple UICollectionViewCell. Lastly, Item is a UICollectionViewCell. Sections has Groups and Groups has Items. See below figure for basic understanding.

Basic demonstration of Section, Group and Item inside UICollectionView Compositional Layout

Let’s create our first and fresh layout.

Above code snippet will produce below layout. Also at Line: 74, you will see orthogonalScrollingBehavior property is equal to .groupPaging. This property setup will make our layout scrollable by groups.

Also we have other useful options for orthogonalScrollingBehavior. Let’s take a quick look of them.

Continuous

It removes pageable scroll behaviour and makes our group scrollable continuously.

ContinuousGroupLeadingBoundary

It behaves like both .groupPaging and .continues options. You can scroll the group continuously but when you stop scrolling your group will fit the screen like .groupPaging smoothly.

None

The section does not allow users to scroll its content orthogonally. In our case, all the groups that we created will be layout vertically inside its own section.

The original article is on AppCircle.io’s blog. Click here to read more.

Follow me on Twitter, GitHub and Linkedin.

--

--

Enes Buğra Yenidünya

iOS Engineer — Freelancer #iOS #swift #mobileappdevelopment #software #apple