UICollectionView
Swift
iOS Development
UICollectionViewCell
Programming Tutorial

How to set UICollectionViewCell Width and Height programmatically

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Setting UICollectionViewCell size programmatically usually means working with a flow layout and deciding whether your cells are fixed-size or responsive to the available width. UIKit gives you two main approaches: assign a single itemSize on the layout, or implement UICollectionViewDelegateFlowLayout and calculate the size for each item.

The right choice depends on how dynamic the grid needs to be. Fixed sizes are simpler, while delegate-based sizing is better when the number of columns should adapt to screen size.

Set a Fixed Cell Size on the Layout

If every cell should have the same width and height, configure the collection view’s UICollectionViewFlowLayout.

swift
1import UIKit
2
3final class FixedGridViewController: UIViewController {
4    private var collectionView: UICollectionView!
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8
9        let layout = UICollectionViewFlowLayout()
10        layout.itemSize = CGSize(width: 120, height: 160)
11        layout.minimumLineSpacing = 12
12        layout.minimumInteritemSpacing = 12
13        layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
14
15        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
16        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
17        view.addSubview(collectionView)
18    }
19}

This is the easiest option when you already know the target size. It works well for card-style layouts, photo grids with fixed thumbnails, or menu screens where every cell shares the same design.

Calculate Responsive Sizes with the Delegate

For more control, adopt UICollectionViewDelegateFlowLayout and implement collectionView(_:layout:sizeForItemAt:). This lets you compute a cell size from the collection view width, spacing, and desired number of columns.

swift
1import UIKit
2
3final class GridViewController: UIViewController, UICollectionViewDelegateFlowLayout {
4    private var collectionView: UICollectionView!
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8
9        let layout = UICollectionViewFlowLayout()
10        layout.minimumLineSpacing = 12
11        layout.minimumInteritemSpacing = 12
12
13        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
14        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
15        collectionView.delegate = self
16        view.addSubview(collectionView)
17    }
18
19    func collectionView(
20        _ collectionView: UICollectionView,
21        layout collectionViewLayout: UICollectionViewLayout,
22        sizeForItemAt indexPath: IndexPath
23    ) -> CGSize {
24        let columns: CGFloat = 2
25        let horizontalInsets: CGFloat = 16 + 16
26        let interItemSpacing: CGFloat = 12
27        let totalSpacing = horizontalInsets + interItemSpacing * (columns - 1)
28
29        let availableWidth = collectionView.bounds.width - totalSpacing
30        let width = floor(availableWidth / columns)
31
32        return CGSize(width: width, height: width * 1.2)
33    }
34}

This pattern keeps the layout consistent across different screen widths. On an iPhone in portrait, you might show two columns; on a wider screen, you could switch to three or four.

Adjust for Rotation and Size Changes

Collection view bounds can change after rotation, split-view resizing, or other layout updates. If cell sizes depend on collectionView.bounds.width, invalidate the layout when the size changes so the delegate is asked again.

swift
1override func viewDidLayoutSubviews() {
2    super.viewDidLayoutSubviews()
3    collectionView.collectionViewLayout.invalidateLayout()
4}

That is often enough for a basic flow layout. If you want to avoid invalidating on every layout pass, you can store the previous size and invalidate only when the bounds actually change.

Choose Between Layout-Level and Delegate-Level Sizing

Use itemSize when every cell can be described with one constant size. It is simpler and easier to reason about.

Use sizeForItemAt when:

  • cell width depends on screen size
  • different sections need different sizes
  • certain items should be larger than others
  • spacing and column count are part of the calculation

For modern iOS layouts, UICollectionViewCompositionalLayout is another option, but for many apps UICollectionViewFlowLayout plus sizeForItemAt is still the most direct answer to “set width and height programmatically.”

Common Pitfalls

The most common issue is forgetting to subtract section insets and inter-item spacing when calculating width. If you divide the full screen width by the number of columns, cells will overflow or wrap unexpectedly.

Another problem is setting both itemSize and implementing sizeForItemAt without knowing which behavior you want. The delegate method gives per-item sizing, so mixing both approaches can confuse future maintenance.

Self-sizing cells are another source of conflict. If you rely on Auto Layout and estimated item sizes, manually forcing a different size can produce warnings or clipped content. Pick one sizing strategy for that screen.

Finally, do not calculate with view.frame.width too early in the lifecycle. Layout dimensions are more reliable once the collection view has its final bounds.

Summary

  • Set layout.itemSize when all cells share one fixed size.
  • Use collectionView(_:layout:sizeForItemAt:) when the size depends on available width or item type.
  • Subtract insets and spacing before dividing width into columns.
  • Invalidate the layout when bounds changes should trigger a recalculation.
  • Avoid mixing manual sizing and self-sizing unless you understand how they interact.

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.