UICollectionViewDelegateFlowLayout
iOS development
Swift
UICollectionView
layout customization

How to set UICollectionViewDelegateFlowLayout?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

UICollectionViewDelegateFlowLayout lets your code control item size, spacing, and section insets for a flow-layout collection view at runtime. It is the usual choice when the layout depends on screen width, orientation, or section-specific rules and you want more control than the default storyboard settings provide.

Wire the Delegate Correctly

The first requirement is simple: the collection view's delegate must actually point to an object that conforms to UICollectionViewDelegateFlowLayout.

swift
1import UIKit
2
3final class GridViewController: UIViewController, UICollectionViewDelegateFlowLayout {
4    @IBOutlet private weak var collectionView: UICollectionView!
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        collectionView.delegate = self
9    }
10}

If the delegate is not assigned, the layout callbacks are never called, which makes every sizing bug look mysterious even though the setup is the real problem.

Implement sizeForItemAt

The method most people need first is collectionView(_:layout:sizeForItemAt:). The common pattern is to compute a width from the collection view bounds, section insets, and inter-item spacing.

swift
1func collectionView(
2    _ collectionView: UICollectionView,
3    layout collectionViewLayout: UICollectionViewLayout,
4    sizeForItemAt indexPath: IndexPath
5) -> CGSize {
6    let leftRightInset: CGFloat = 16
7    let spacing: CGFloat = 8
8    let columns: CGFloat = 2
9
10    let totalSpacing = leftRightInset * 2 + spacing * (columns - 1)
11    let width = (collectionView.bounds.width - totalSpacing) / columns
12
13    return CGSize(width: width, height: width * 1.2)
14}

The important part is subtracting all spacing before dividing. If you divide too early, cells will not fit cleanly across the row.

Configure Insets and Spacing

UICollectionViewDelegateFlowLayout also lets you define section padding and row spacing dynamically.

swift
1func collectionView(
2    _ collectionView: UICollectionView,
3    layout collectionViewLayout: UICollectionViewLayout,
4    insetForSectionAt section: Int
5) -> UIEdgeInsets {
6    UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
7}
8
9func collectionView(
10    _ collectionView: UICollectionView,
11    layout collectionViewLayout: UICollectionViewLayout,
12    minimumLineSpacingForSectionAt section: Int
13) -> CGFloat {
14    8
15}
16
17func collectionView(
18    _ collectionView: UICollectionView,
19    layout collectionViewLayout: UICollectionViewLayout,
20    minimumInteritemSpacingForSectionAt section: Int
21) -> CGFloat {
22    8
23}

These methods are useful even when the overall layout is simple, because they keep the spacing logic close to the sizing logic.

Handle Rotation and Size Changes

Collection views often break when the device rotates or the app enters split-screen mode because the item size was calculated once and then never refreshed. If the layout depends on width, invalidate it when the bounds change.

swift
1override func viewWillLayoutSubviews() {
2    super.viewWillLayoutSubviews()
3    collectionView.collectionViewLayout.invalidateLayout()
4}

That tells the flow layout to ask for item sizes again with the new dimensions.

Vary Layout by Section or Item

A major benefit of the delegate approach is that it can return different sizes or insets based on section or index path. For example, a featured first section can use a full-width card while the rest of the collection uses a grid.

swift
1func collectionView(
2    _ collectionView: UICollectionView,
3    layout collectionViewLayout: UICollectionViewLayout,
4    sizeForItemAt indexPath: IndexPath
5) -> CGSize {
6    if indexPath.section == 0 {
7        return CGSize(width: collectionView.bounds.width - 32, height: 180)
8    }
9
10    let spacing: CGFloat = 8
11    let inset: CGFloat = 16
12    let columns: CGFloat = 2
13    let total = inset * 2 + spacing * (columns - 1)
14    let width = (collectionView.bounds.width - total) / columns
15    return CGSize(width: width, height: width)
16}

That kind of rule is exactly what makes the delegate protocol useful.

Know When Flow Layout Is No Longer the Right Tool

Flow layout is excellent for grids and row-based arrangements. If the screen starts looking like a magazine layout with nested groups, orthogonal scrolling sections, or highly irregular item placement, compositional layout may express the design more clearly.

The engineering rule is not to use the fanciest layout API. It is to use the simplest one that still matches the UI honestly.

Common Pitfalls

  • Forgetting to set the collection view delegate, so layout methods never run.
  • Calculating cell width without subtracting all insets and spacing first.
  • Hardcoding sizes that break on rotation or split-screen changes.
  • Returning spacing values in code that conflict with assumptions from Interface Builder.
  • Forcing a complex custom design into flow-layout math when a different layout system would be clearer.

Summary

  • Conform to UICollectionViewDelegateFlowLayout and assign the collection view delegate.
  • Implement sizeForItemAt when item size depends on runtime dimensions.
  • Use the inset and spacing delegate methods so layout math stays explicit.
  • Invalidate the layout when the collection view width changes.
  • Use flow layout for grids and rows, and switch tools only when the design has clearly outgrown it.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.