UICollectionView
Full Width Cells
AutoLayout
Dynamic Height
iOS Development

UICollectionView, full width cells, allow autolayout dynamic height?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

UICollectionView can absolutely support full-width cells with dynamic height, but the layout and constraints must be configured carefully. Many issues come from mixing manual sizing with Auto Layout self-sizing rules. This guide shows a stable setup that works with modern iOS collection views.

Full-Width Layout Strategy

For list-like screens, a flow layout with zero horizontal section insets and one item per row is the simplest approach. You then let Auto Layout determine height.

swift
1import UIKit
2
3final class FeedViewController: UIViewController {
4    @IBOutlet private weak var collectionView: UICollectionView!
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8
9        let layout = UICollectionViewFlowLayout()
10        layout.scrollDirection = .vertical
11        layout.minimumLineSpacing = 12
12        layout.minimumInteritemSpacing = 0
13        layout.sectionInset = .zero
14        layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
15
16        collectionView.collectionViewLayout = layout
17        collectionView.contentInset = UIEdgeInsets(top: 12, left: 0, bottom: 12, right: 0)
18    }
19}

estimatedItemSize is key for self-sizing. Without it, Auto Layout height calculation may never run.

Cell Constraints for Dynamic Height

Inside the cell, build one vertical constraint chain from top anchor to bottom anchor. Any missing bottom constraint can cause ambiguous height.

swift
1final class ArticleCell: UICollectionViewCell {
2    let titleLabel = UILabel()
3    let subtitleLabel = UILabel()
4
5    override init(frame: CGRect) {
6        super.init(frame: frame)
7        setupViews()
8    }
9
10    required init?(coder: NSCoder) {
11        super.init(coder: coder)
12        setupViews()
13    }
14
15    private func setupViews() {
16        contentView.backgroundColor = .secondarySystemBackground
17        contentView.layer.cornerRadius = 10
18
19        titleLabel.numberOfLines = 0
20        subtitleLabel.numberOfLines = 0
21
22        let stack = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel])
23        stack.axis = .vertical
24        stack.spacing = 8
25        stack.translatesAutoresizingMaskIntoConstraints = false
26
27        contentView.addSubview(stack)
28        NSLayoutConstraint.activate([
29            stack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
30            stack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
31            stack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
32            stack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12)
33        ])
34    }
35}

The stack view simplifies constraint management and improves reliability for variable text lengths.

Ensuring True Full Width

In many designs you still want side padding. You can keep cells effectively full width by subtracting desired horizontal margins in delegate sizing when not using automatic size.

swift
1extension FeedViewController: UICollectionViewDelegateFlowLayout {
2    func collectionView(
3        _ collectionView: UICollectionView,
4        layout collectionViewLayout: UICollectionViewLayout,
5        sizeForItemAt indexPath: IndexPath
6    ) -> CGSize {
7        let horizontalInset: CGFloat = 16
8        let width = collectionView.bounds.width - (horizontalInset * 2)
9        return CGSize(width: width, height: 120) // fallback fixed height
10    }
11}

Use either self-sizing or explicit delegate height logic for a given screen, not both mixed unpredictably.

Data Updates and Layout Invalidations

When content changes after async loading, call performBatchUpdates or reloadItems so layout can recalculate heights.

swift
collectionView.performBatchUpdates(nil)

For major model changes, use a diffable data source snapshot and apply with animation. This keeps updates smooth and avoids stale cached sizes.

Performance Tuning for Self-Sizing Cells

Self-sizing can become expensive when complex cells are measured repeatedly during fast scrolling. Keep cell hierarchies shallow and avoid synchronous image decoding inside cellForItemAt. If height mostly depends on text, precompute attributed text in a view model and cache results so Auto Layout has less work each frame.

For large feeds, consider diffable data sources plus prefetching to reduce layout churn. Measure with Instruments and watch for repeated constraint warnings. Even one ambiguous constraint can trigger expensive fallback passes that degrade scroll smoothness on older devices.

Common Pitfalls

A frequent pitfall is missing preferredLayoutAttributesFitting behavior in heavily customized cells. For most cases it is not needed, but custom subview sizing code can require it.

Another issue is constraining subviews to the cell itself instead of contentView. Self-sizing expects constraints inside contentView, and using the wrong container can break height calculation.

Developers also set estimatedItemSize and still implement fixed delegate heights, which defeats Auto Layout sizing. Choose one strategy per screen.

Finally, performance can degrade when every cell triggers expensive text layout repeatedly. Cache computed view models and avoid unnecessary reloads to keep scrolling smooth.

Summary

  • Full-width dynamic cells work with UICollectionViewFlowLayout and self-sizing.
  • Enable estimatedItemSize and keep a complete top-to-bottom constraint chain.
  • Constrain subviews to contentView, not the cell root view.
  • Avoid conflicting sizing strategies between delegate and Auto Layout.
  • Invalidate layout correctly after asynchronous content updates.

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.