UICollectionView
UITableView
iOS development
Swift programming
mobile app development

How to add HeaderView in UICollectionView like UITableView's tableHeaderView

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

UITableView has a simple tableHeaderView property, but UICollectionView uses a different model: headers are supplementary views provided by the layout. Developers often try to attach a standalone view directly and wonder why it does not behave correctly during scrolling or section updates. To create a table-like header in a collection view, you typically use one of two approaches: a section header supplementary view, or for compositional layout, a boundary supplementary item pinned or non-pinned as needed. This article explains both patterns and when to choose each.

Core Sections

1. Register a reusable header view

Create a subclass of UICollectionReusableView and register it.

swift
1final class FeedHeaderView: UICollectionReusableView {
2    static let reuseID = "FeedHeaderView"
3
4    let titleLabel = UILabel()
5
6    override init(frame: CGRect) {
7        super.init(frame: frame)
8        titleLabel.font = .preferredFont(forTextStyle: .title2)
9        titleLabel.translatesAutoresizingMaskIntoConstraints = false
10        addSubview(titleLabel)
11        NSLayoutConstraint.activate([
12            titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
13            titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8)
14        ])
15    }
16
17    required init?(coder: NSCoder) { fatalError("init(coder:) not implemented") }
18}
swift
1collectionView.register(
2    FeedHeaderView.self,
3    forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
4    withReuseIdentifier: FeedHeaderView.reuseID
5)

2. Flow layout header sizing and data source

With UICollectionViewFlowLayout, set headerReferenceSize and provide the supplementary view.

swift
1if let flow = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
2    flow.headerReferenceSize = CGSize(width: collectionView.bounds.width, height: 72)
3}
4
5func collectionView(_ collectionView: UICollectionView,
6                    viewForSupplementaryElementOfKind kind: String,
7                    at indexPath: IndexPath) -> UICollectionReusableView {
8    let header = collectionView.dequeueReusableSupplementaryView(
9        ofKind: kind,
10        withReuseIdentifier: FeedHeaderView.reuseID,
11        for: indexPath
12    ) as! FeedHeaderView
13    header.titleLabel.text = "Featured"
14    return header
15}

This gives you a section header that scrolls naturally with content.

3. Compositional layout boundary header

For modern layouts, define boundary supplementary items for precise behavior.

swift
1let headerSize = NSCollectionLayoutSize(
2    widthDimension: .fractionalWidth(1.0),
3    heightDimension: .absolute(72)
4)
5let header = NSCollectionLayoutBoundarySupplementaryItem(
6    layoutSize: headerSize,
7    elementKind: UICollectionView.elementKindSectionHeader,
8    alignment: .top
9)
10header.pinToVisibleBounds = false
11
12section.boundarySupplementaryItems = [header]

Set pinToVisibleBounds = true if you want sticky behavior.

4. “Global” header across all sections

If you need a single top header for the whole collection, use section 0 header and keep data model split so it behaves as a global banner. In compositional layout, you can attach a boundary item at layout level for similar effect.

5. Auto layout and dynamic height

Self-sizing headers require estimated sizes and correct constraints. For flow layout, dynamic sizing is trickier than table headers, so compositional layout with estimated dimensions is often cleaner in modern apps.

Validation and production readiness

A reliable implementation should include more than a working snippet. Add a small reproducible dataset or input fixture that exercises expected behavior and edge cases, then codify it in automated tests. Include at least one “happy path,” one malformed input case, and one boundary condition so regressions are caught early. Instrument key steps with structured logs or metrics to make failures diagnosable in runtime environments, not just local development. If performance is relevant, keep a lightweight benchmark that can be rerun after refactors to ensure behavior stays within budget.

Operationally, document assumptions near the code: required library versions, environment variables, timezone/locale expectations, and failure handling strategy. For team workflows, add one integration test that mirrors real usage rather than only unit-level checks. This reduces drift between example code and production behavior. Treat these checks as part of feature completion, because most long-term issues are caused by unvalidated assumptions rather than syntax errors.

Common Pitfalls

  • Expecting a tableHeaderView-style property on UICollectionView.
  • Forgetting to register header class/nib before dequeuing supplementary views.
  • Returning wrong elementKind or reuse identifier, causing runtime crashes.
  • Hardcoding header width once and ignoring orientation/size class changes.
  • Attempting global header behavior without a clear section/layout strategy.

Summary

In UICollectionView, headers are layout-driven supplementary views, not direct container properties. Implement them by registering a reusable header, configuring layout header size, and returning the view through the data source. Prefer compositional layout for flexible modern behavior, especially sticky or dynamically sized headers. With the right pattern, you can reproduce and exceed table-style header behavior while keeping collection view architecture clean.


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.