UICollectionView
iOS Development
Swift Programming
Mobile App Design
Layout Techniques

Left Align Cells in UICollectionView

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

UICollectionViewFlowLayout arranges items row by row, but default spacing can look centered rather than left-aligned when item widths vary. Many apps need consistent left alignment for tag lists, filters, and chip-style interfaces. A custom flow layout gives precise control while preserving collection view performance.

Why Default Flow Layout Looks Misaligned

Flow layout places items based on minimum spacing rules and available line width. When cells self-size, each row can appear to have inconsistent leading space. Left alignment requires adjusting each item frame after layout attributes are calculated.

The usual approach is subclassing UICollectionViewFlowLayout and overriding layoutAttributesForElements.

Custom Left-Aligned Flow Layout

The layout below rewrites each row so items begin at the same left inset.

swift
1import UIKit
2
3final class LeftAlignedFlowLayout: UICollectionViewFlowLayout {
4    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
5        guard let attributes = super.layoutAttributesForElements(in: rect) else {
6            return nil
7        }
8
9        var left = sectionInset.left
10        var currentRowY: CGFloat = -1.0
11
12        for attr in attributes where attr.representedElementCategory == .cell {
13            if currentRowY < 0 || abs(attr.frame.origin.y - currentRowY) > 1.0 {
14                currentRowY = attr.frame.origin.y
15                left = sectionInset.left
16            }
17
18            attr.frame.origin.x = left
19            left += attr.frame.width + minimumInteritemSpacing
20        }
21
22        return attributes
23    }
24
25    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
26        return true
27    }
28}

Use this layout when creating the collection view or assign it in Interface Builder through code.

Self-Sizing Cells and Auto Layout

Left alignment works best when item sizes are deterministic. For dynamic text chips, configure estimated size and ensure content constraints are complete.

swift
1let layout = LeftAlignedFlowLayout()
2layout.sectionInset = UIEdgeInsets(top: 12, left: 16, bottom: 12, right: 16)
3layout.minimumInteritemSpacing = 8
4layout.minimumLineSpacing = 8
5layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
6
7let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

If labels truncate or widths oscillate during reload, verify content hugging and compression priorities in the cell class.

Modern Alternative with Compositional Layout

For iOS versions where compositional layout is available, you can also build left-leaning groups with estimated item sizes. That can simplify section-based designs, though custom flow layout remains straightforward for single chip rows.

Compositional layout is especially useful when combining left-aligned chips with other section types in one collection view.

Section-Specific Styling

Some product screens need different alignment behavior per section, for example left-aligned filter chips in one section and fixed-width cards in another. In that case, either implement a custom layout that branches by section index or move to compositional layout with per-section groups. Keep this decision explicit in code comments so future refactors do not accidentally merge incompatible assumptions.

When animations are involved, such as inserting or deleting chips, verify that layout updates and data source snapshots stay synchronized. Left alignment logic can appear correct at rest but produce temporary jumps if updates are applied out of order.

Testing and Runtime Behavior

Test with short text, long text, dynamic type sizes, and device rotation. Orientation changes can expose row recalculation bugs if layout invalidation is incomplete.

Also verify behavior with multiple sections. If each section needs different insets, override layout methods carefully or use separate section configurations.

For large datasets, avoid heavy work in layout overrides beyond frame adjustment. Expensive per-item calculations can affect scroll smoothness.

Common Pitfalls

A common mistake is mutating layout attributes returned by super without copying when required by custom setups. In most simple flow layout cases this is fine, but complex interactions can require defensive copies.

Another issue is forgetting to invalidate layout on bounds changes. Without invalidation, rotation and size class changes can leave stale item positions.

Developers also set estimated size but forget proper auto layout constraints in cells. That causes unstable widths and jumpy reflow.

Finally, mixing manual sizeForItemAt logic with automatic sizing can create conflicting item widths. Choose one sizing strategy per section when possible.

Summary

  • Subclass flow layout and adjust item x positions per row for left alignment.
  • Use clear section insets and spacing values for consistent chip layouts.
  • Configure self-sizing cells carefully when text length varies.
  • Invalidate layout on bounds changes to support rotation and resizing.
  • Benchmark large datasets to ensure custom layout code stays lightweight.

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.