UICollectionView
Self Sizing Cells
Auto Layout
iOS Development
Swift Programming

UICollectionView Self Sizing Cells with Auto Layout

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Self-sizing collection-view cells let the cell height or width follow the content instead of a hardcoded size. The feature works well with Auto Layout, but only if the collection view layout, the cell constraints, and the content’s intrinsic size all agree on how the cell should be measured.

Enable Self-Sizing in the Layout

For a UICollectionViewFlowLayout, the usual starting point is to give the layout an estimated item size.

swift
1import UIKit
2
3let layout = UICollectionViewFlowLayout()
4layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
5layout.minimumLineSpacing = 12
6layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)

That tells the flow layout to ask Auto Layout for the final size instead of requiring you to return a fixed item size from the delegate.

Build the Cell with Complete Constraints

The cell must be fully constrained from edge to edge. If any subview is missing a top, bottom, leading, or trailing path to the contentView, the layout engine cannot infer the correct size.

swift
1import UIKit
2
3final class TagCell: UICollectionViewCell {
4    static let reuseID = "TagCell"
5
6    private let label: UILabel = {
7        let label = UILabel()
8        label.numberOfLines = 0
9        label.translatesAutoresizingMaskIntoConstraints = false
10        return label
11    }()
12
13    override init(frame: CGRect) {
14        super.init(frame: frame)
15
16        contentView.backgroundColor = .secondarySystemBackground
17        contentView.layer.cornerRadius = 10
18        contentView.addSubview(label)
19
20        NSLayoutConstraint.activate([
21            label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
22            label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12),
23            label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 12),
24            label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -12)
25        ])
26    }
27
28    required init?(coder: NSCoder) {
29        fatalError("init(coder:) has not been implemented")
30    }
31
32    func configure(text: String) {
33        label.text = text
34    }
35}

The label has a clear padded box, so Auto Layout can compute the cell’s content size.

Register and Use the Cell Normally

Once the layout and cell are configured, the collection view setup remains standard.

swift
1final class TagsViewController: UIViewController, UICollectionViewDataSource {
2    private let items = ["Short", "A much longer line of text that needs wrapping"]
3    private lazy var collectionView: UICollectionView = {
4        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
5        cv.translatesAutoresizingMaskIntoConstraints = false
6        cv.backgroundColor = .systemBackground
7        cv.dataSource = self
8        cv.register(TagCell.self, forCellWithReuseIdentifier: TagCell.reuseID)
9        return cv
10    }()
11
12    private let layout: UICollectionViewFlowLayout = {
13        let layout = UICollectionViewFlowLayout()
14        layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
15        return layout
16    }()
17
18    override func viewDidLoad() {
19        super.viewDidLoad()
20        view.addSubview(collectionView)
21        NSLayoutConstraint.activate([
22            collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
23            collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
24            collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
25            collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
26        ])
27    }
28
29    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
30        items.count
31    }
32
33    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
34        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TagCell.reuseID, for: indexPath) as! TagCell
35        cell.configure(text: items[indexPath.item])
36        return cell
37    }
38}

Multi-Line Labels Need a Real Width Constraint

A common trap is using a label with numberOfLines = 0 but never giving Auto Layout enough information about the final width. The cell can only derive a height from wrapped text after it knows how wide the text area is meant to be.

For full-width list-style cells, the flow layout’s available width plus your insets usually defines that naturally. For more complex layouts, you may need a custom layout or sizing override.

When preferredLayoutAttributesFitting Helps

If a cell still sizes incorrectly, override preferredLayoutAttributesFitting(_:) and force a layout pass before measuring. That is often helpful for custom content or older layout behavior.

Common Pitfalls

The biggest mistake is incomplete constraints inside the cell. Another is leaving estimatedItemSize unset, which prevents the flow layout from asking Auto Layout for dynamic sizing. Developers also often expect multi-line labels to self-size without a meaningful width context. Finally, mixing manual size delegate methods with self-sizing behavior can produce confusing results because the layout receives conflicting instructions.

Summary

  • Set estimatedItemSize on the collection-view flow layout.
  • Fully constrain the cell’s content to contentView on all sides.
  • Make sure multi-line content has a clear width to wrap within.
  • Register and use the cell normally; self-sizing happens through Auto Layout.
  • If sizing still looks wrong, inspect constraints first before adding manual measurement code.

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.