UICollectionView
Auto Layout
iOS Development
Swift Programming
Interface Design

Specifying one Dimension of Cells in UICollectionView using 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

In UICollectionView, Auto Layout can determine a cell’s size, but it works best when you give the layout enough information. A common requirement is to fix one dimension, such as the width, and let Auto Layout compute the other, such as the height. The usual solution is to constrain one dimension externally and let the cell’s internal constraints define the other dimension naturally.

The Core Pattern

For self-sizing cells, the collection view layout needs:

  • an estimated size
  • a cell whose internal constraints fully define the variable dimension
  • one fixed or externally known dimension

For example, if the width is fixed by the layout, the cell can use Auto Layout to compute its height from labels, images, and padding.

Flow Layout Example With Fixed Width

In a flow layout, you can calculate the width and let Auto Layout determine the height.

swift
1import UIKit
2
3final class ViewController: UIViewController, UICollectionViewDelegateFlowLayout {
4    @IBOutlet weak var collectionView: UICollectionView!
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8
9        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
10            layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
11        }
12    }
13
14    func collectionView(
15        _ collectionView: UICollectionView,
16        layout collectionViewLayout: UICollectionViewLayout,
17        sizeForItemAt indexPath: IndexPath
18    ) -> CGSize {
19        let horizontalInset: CGFloat = 32
20        let width = collectionView.bounds.width - horizontalInset
21        return CGSize(width: width, height: UICollectionViewFlowLayout.automaticSize.height)
22    }
23}

The important idea is that the width is known, and the cell’s internal constraints decide the height.

Build the Cell So Auto Layout Can Succeed

Inside the cell, the content must be fully constrained from top to bottom if height is the flexible dimension.

swift
1final class MessageCell: UICollectionViewCell {
2    @IBOutlet weak var titleLabel: UILabel!
3
4    override func awakeFromNib() {
5        super.awakeFromNib()
6        titleLabel.numberOfLines = 0
7    }
8}

If the label, image view, and container views do not have a complete vertical constraint chain, the layout engine cannot infer the correct height.

A typical successful setup is:

  • subviews pinned to the content view edges with padding
  • intrinsic content size from labels or images
  • no ambiguous vertical constraints

Alternative: Fixed Height, Flexible Width

The same principle works the other way around. You can fix the height and let the width be derived by content, though that is less common in scrolling grids.

The rule stays the same: one dimension comes from the layout, the other must be solvable by constraints and intrinsic content size.

Use preferredLayoutAttributesFitting When Needed

For more control, override preferredLayoutAttributesFitting(_:) in the cell.

swift
1override func preferredLayoutAttributesFitting(
2    _ layoutAttributes: UICollectionViewLayoutAttributes
3) -> UICollectionViewLayoutAttributes {
4    setNeedsLayout()
5    layoutIfNeeded()
6
7    let size = contentView.systemLayoutSizeFitting(
8        CGSize(width: layoutAttributes.size.width, height: UIView.layoutFittingCompressedSize.height),
9        withHorizontalFittingPriority: .required,
10        verticalFittingPriority: .fittingSizeLevel
11    )
12
13    layoutAttributes.frame.size.height = ceil(size.height)
14    return layoutAttributes
15}

This is useful when default self-sizing is not enough or you need more predictable fitting behavior.

Compositional Layout Needs the Same Logic

If you are using compositional layout, the API changes but the sizing idea does not. For example, you might use an estimated height with a fractional width.

swift
1let itemSize = NSCollectionLayoutSize(
2    widthDimension: .fractionalWidth(1.0),
3    heightDimension: .estimated(80)
4)

That means:

  • width is fixed relative to the container
  • height grows according to content and Auto Layout

The mental model is the same as flow layout, even though the configuration is different.

Common Pitfalls

A common mistake is enabling automatic sizing without giving the cell a complete constraint chain in the flexible dimension. Then the size becomes ambiguous or wrong.

Another issue is trying to let Auto Layout determine both dimensions in a context where the layout really expects one dimension to be externally constrained.

Developers also sometimes set estimatedItemSize but still return fixed hard-coded sizes elsewhere, which cancels out self-sizing behavior.

Finally, remember that UILabel often needs numberOfLines = 0 to expand vertically based on text content.

Summary

  • To size one collection-view cell dimension with Auto Layout, fix one dimension and let constraints define the other.
  • Use self-sizing cells with estimatedItemSize or estimated dimensions in the layout.
  • Make sure the cell’s content has a complete constraint chain in the flexible dimension.
  • Override preferredLayoutAttributesFitting(_:) when you need more control.
  • The same sizing principle applies whether you use flow layout or compositional layout.

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.