skip to content

In UIKit, how does UICollectionViewCompositionalLayout build a home screen with a sideways carousel, a two-column grid and a vertical list from items, groups and sections?

level: middleimportance: should knowfreq 40%

answer

  1. four nested levels
  2. fractions of the container
  3. one section per index
  4. orthogonal means across the main axis

basics

~20 s

UICollectionViewCompositionalLayout nests items in groups and groups in sections, each sized with fractional, absolute or estimated dimensions. A section provider returns a different NSCollectionLayoutSection per index: one with orthogonalScrollingBehavior for the carousel, a two-item group for the grid, and a list section.

solid answer

~40 s

Compositional layout (iOS 13) describes geometry as nested values: an `NSCollectionLayoutItem` sits in an `NSCollectionLayoutGroup`, groups repeat inside an `NSCollectionLayoutSection`, and sections make the layout. Each size is an `NSCollectionLayoutSize` of two `NSCollectionLayoutDimension`s: `.fractionalWidth` or `.fractionalHeight` of the container, `.absolute` points, or `.estimated` for self-sizing. `init(sectionProvider:)` returns a different section for each index and layout environment. The featured carousel is a horizontal group 85% wide in a section whose `orthogonalScrollingBehavior` is `.groupPaging` or `.continuous`, so that section scrolls sideways inside the vertical collection view. Saved searches use `NSCollectionLayoutGroup.horizontal(layoutSize:repeatingSubitem:count:)` (iOS 16) with a count of 2. Listings use `NSCollectionLayoutSection.list(using:layoutEnvironment:)` with a `UICollectionLayoutListConfiguration`, which gives table-style rows and swipe actions. Estimated heights let cells self-size, but item content insets are ignored on an estimated axis, so spacing comes from the group or section.

code

swift · 30 lines
swift
import UIKit

enum HomeSection: Int { case featured, savedSearches, listings }

@MainActor func makeHomeLayout() -> UICollectionViewCompositionalLayout {
    UICollectionViewCompositionalLayout { sectionIndex, environment in
        switch HomeSection(rawValue: sectionIndex) {
        case .featured:
            let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1),
                                                                heightDimension: .fractionalHeight(1)))
            let group = NSCollectionLayoutGroup.horizontal(
                layoutSize: .init(widthDimension: .fractionalWidth(0.85), heightDimension: .absolute(220)),
                subitems: [item])
            let section = NSCollectionLayoutSection(group: group)
            section.orthogonalScrollingBehavior = .groupPaging      // the carousel scrolls sideways
            section.interGroupSpacing = 12
            return section
        case .savedSearches:
            let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(0.5),
                                                                heightDimension: .estimated(80)))
            let group = NSCollectionLayoutGroup.horizontal(
                layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(80)),
                repeatingSubitem: item, count: 2)                    // iOS 16+
            return NSCollectionLayoutSection(group: group)
        case .listings, nil:
            let config = UICollectionLayoutListConfiguration(appearance: .plain)
            return NSCollectionLayoutSection.list(using: config, layoutEnvironment: environment)
        }
    }
}

go deeper

for a junior

Recall the nesting of item, group, section and layout, and the three dimension kinds: fractional, absolute and estimated.

for a middle

Build a mixed screen with a section provider: an orthogonal carousel, a repeated-item grid and a list section, and explain what fractional sizes are measured against.

for a senior

Handle self-sizing with estimated dimensions, the ignored-insets rule, adaptive columns from the layout environment, and debugging with visualDescription().

for a principal

Judge whether compositional layout plus list configurations should replace table views as the team's single list stack, and what that costs to adopt.

## The four-level model `UICollectionViewCompositionalLayout` (iOS 13) is a `UICollectionViewLayout` you build from small descriptions instead of subclassing. Apple's documentation describes building it up from **items** into a **group**, from groups into a **section**, and from sections into the full layout: - An **item** (`NSCollectionLayoutItem`) is the space for one cell. - A **group** (`NSCollectionLayoutGroup`) lays items out horizontally, vertically or in custom frames. A group is itself a kind of item, so groups nest. - A **section** (`NSCollectionLayoutSection`) repeats its group for as many items as the data source's section holds, with `interGroupSpacing` between repeats and `contentInsets` around them. - The **layout** combines sections, either one section definition for all or a **section provider** closure per index. ## Dimensions Every item and group has an `NSCollectionLayoutSize` with a width and a height dimension: | Dimension | Meaning | |---|---| | `.fractionalWidth(x)` / `.fractionalHeight(x)` | a fraction of the **container**: the enclosing group for an item, the section's available area for a section's outer group | | `.absolute(points)` | a fixed size in points | | `.estimated(points)` | a starting guess; the cell's Auto Layout content decides the final size | | `.uniformAcrossSiblings(estimate:)` (iOS 17) | grows to the largest sibling; the header warns it is expensive for many items | Fractions are relative to the container, not the screen: the header describes a fractional width as a fraction of the containing group's width, so an item at `.fractionalWidth(0.5)` takes half of its group. ## One section per job The listings home screen needs three shapes, so `init(sectionProvider:)` switches on the section index: 1. **Featured homes**: an item filling its group, a horizontal group `.fractionalWidth(0.85)` wide and `.absolute(220)` tall, and a section whose `orthogonalScrollingBehavior` is `.groupPaging`, so each swipe advances one home with the next one peeking in. 2. **Saved searches**: an item `.fractionalWidth(0.5)` wide with an `.estimated(80)` height, in a horizontal group built with `horizontal(layoutSize:repeatingSubitem:count:)` and a count of 2, which gives two columns. The header says the caller must make sure the group's size fits that many items. 3. **Listings**: `NSCollectionLayoutSection.list(using:layoutEnvironment:)` with a `UICollectionLayoutListConfiguration`, for full-width rows with separators. The provider also receives an `NSCollectionLayoutEnvironment`, so it can read `container.effectiveContentSize` and the trait collection and choose, say, three grid columns on an iPad. ## Orthogonal scrolling `orthogonalScrollingBehavior` defaults to `.none`. Any other value lays the section's content out **orthogonal to the main axis**, so a section scrolls horizontally inside a vertically scrolling collection view. The header lists the options: - `.continuous`, free scrolling. - `.continuousGroupLeadingBoundary`, coming to rest at the leading edge of a group. - `.paging`, page by page. - `.groupPaging` and `.groupPagingCentered`, one group at a time, the second centring each group. Since iOS 17, `orthogonalScrollingProperties` also sets the deceleration rate and bounce. This replaces the older trick of embedding a second collection view inside a cell. ## Lists inside a compositional layout `UICollectionLayoutListConfiguration` (iOS 14) brings table-style lists to collection views: appearances such as `.plain` and `.insetGrouped`, header modes, separators, and `leadingSwipeActionsConfigurationProvider` and `trailingSwipeActionsConfigurationProvider` for swipe actions. `UICollectionViewCompositionalLayout.list(using:)` makes a whole layout a list; the section form mixes a list with other sections, as here. ## Headers and other supplementary views Section headers are **boundary supplementary items**: an `NSCollectionLayoutBoundarySupplementaryItem` with a size, an element kind such as `UICollectionView.elementKindSectionHeader` and an alignment such as `.top`, added to the section's `boundarySupplementaryItems`. Setting `pinToVisibleBounds` keeps a header stuck to the top while its section scrolls. The views themselves come from a `UICollectionView.SupplementaryRegistration` and `dequeueConfiguredReusableSupplementary(using:for:)`, the supplementary counterpart of cell registration, called from the diffable data source's `supplementaryViewProvider`. ## Self-sizing and spacing traps - An item's `contentInsets` are **ignored on any axis with an estimated dimension**, as the header notes; space self-sizing cells with the group's `interItemSpacing`, the section's `interGroupSpacing` or section insets. - Self-sizing needs the cell's constraints to determine its height from the content view; how to write those constraints belongs to the lesson on Auto Layout. - Since iOS 16, `selfSizingInvalidation` on the collection view lets a cell resize after `invalidateIntrinsicContentSize()`; `.enabledIncludingConstraints` also reacts to Auto Layout changes inside the content view. - When a group looks wrong, `visualDescription()` on the group prints an ASCII rendering to the console. The layout is independent of the data source: it works with an index-path data source as well as a diffable one.

  • How does a section adapt its column count to an iPad or a rotated phone?
    The section provider receives an `NSCollectionLayoutEnvironment`. Read `environment.container.effectiveContentSize.width`, or the environment's trait collection, choose the column count, and build the group from it. The provider runs again when the layout is invalidated, for example after a size change.
  • How do self-sizing cells work in a compositional layout?
    Give the item and group an `.estimated` height; the cell's Auto Layout content then determines the real height. Item content insets do not apply on that axis, so use spacing instead. Since iOS 16, `selfSizingInvalidation` lets a cell that changes content call `invalidateIntrinsicContentSize()` and be resized.
  • How do you debug a group that lays its items out wrongly?
    Print `visualDescription()` on the `NSCollectionLayoutGroup`; the header says it renders an ASCII picture of the group to the console. Check that fractional sizes refer to the container you expect and that a repeated item count fits the group's size.

  • Fractional widths are always a fraction of the collection view's width.
  • A horizontal carousel row requires a second UICollectionView inside a cell.
  • Setting the layout configuration's scrollDirection to horizontal makes just the carousel scroll sideways.
  • An item's contentInsets add padding around self-sizing cells with estimated heights.
  • Compositional layout only works with a diffable data source.