UICollectionView
cell width
dynamic layout
label width
iOS development

Dynamic cell width of UICollectionView depending on label width

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Dynamic collection view cell widths based on label content are common in tag chips, filters, and segmented chooser interfaces. The layout must account for text size, padding, and spacing while remaining stable during scrolling. A robust implementation computes widths deterministically and invalidates layout when content changes.

Designing a fix that survives real usage requires more than one passing example. Treat each solution as a small interface contract with explicit assumptions, clear failure behavior, and repeatable verification steps.

Sizing Strategy For Collection Cells

1. Measure Text With Font Aware Bounding

Compute label width using the exact font and add horizontal padding for chip styling. Keep this logic in one helper so design updates stay centralized.

swift
1func cellWidth(for text: String, font: UIFont, horizontalPadding: CGFloat) -> CGFloat {
2    let attributes: [NSAttributedString.Key: Any] = [.font: font]
3    let size = (text as NSString).size(withAttributes: attributes)
4    return ceil(size.width + horizontalPadding * 2)
5}
6
7let width = cellWidth(for: "Architecture", font: .systemFont(ofSize: 15), horizontalPadding: 12)

The baseline implementation should stay intentionally simple. A small, transparent first version makes review faster and gives you a reliable reference point for later optimization.

2. Return Sizes Through Flow Layout Delegate

In UICollectionViewDelegateFlowLayout, calculate size per item and keep height fixed or responsive as required. Avoid expensive repeated calculations by caching widths for stable datasets.

swift
1func collectionView(
2    _ collectionView: UICollectionView,
3    layout collectionViewLayout: UICollectionViewLayout,
4    sizeForItemAt indexPath: IndexPath
5) -> CGSize {
6    let text = items[indexPath.item]
7    let width = cellWidth(for: text, font: .systemFont(ofSize: 15), horizontalPadding: 12)
8    return CGSize(width: width, height: 32)
9}
10
11// when data changes
12collectionView.collectionViewLayout.invalidateLayout()

After baseline correctness, focus on operational hardening. Add input validation, timeout boundaries, and structured logging around critical branches so failures can be diagnosed quickly in real environments.

3. Handle Dynamic Type And Localization

Wider strings in localized languages and larger accessibility text sizes can break naive width assumptions. Test with long labels and adjust minimum and maximum widths to protect layout integrity.

Production confidence comes from repeatable checks. Add one normal-case test, one edge-case test, and one failure-path assertion in automation. This keeps behavior stable as dependencies and surrounding code evolve.

Where practical, include rollout safeguards such as feature toggles or rollback instructions. Recovery planning lowers deployment risk and shortens incident response time when unexpected runtime conditions appear.

A robust implementation also needs explicit operational boundaries. Document what inputs are supported, which failures are retriable, and which errors should fail fast. When these rules remain implicit, downstream callers invent their own assumptions and behavior drifts across services, scripts, or user interfaces. A short contract section close to the implementation often prevents weeks of confusion later.

Verification should include realistic data, not only toy examples. Add one scenario that mirrors production volume or shape, plus one malformed-input case and one dependency-failure case. These tests should run in automation on every change. Fast, repeatable checks are the most reliable way to keep behavior stable when dependencies change, runtime versions shift, or contributors refactor code with good intentions.

Finally, define release safety mechanics before rollout. Feature toggles, staged deployment, or a clear rollback procedure can turn a risky change into a controlled experiment. Even well designed code can fail under unexpected traffic patterns or infrastructure conditions. Teams that plan recovery ahead of time restore service faster and continue shipping with confidence.

Common Pitfalls

  • Using hardcoded cell widths that clip translated or larger text.
  • Measuring with a different font than the actual label font.
  • Recomputing widths excessively on every scroll event.
  • Forgetting to invalidate layout after content or font changes.
  • Ignoring inter-item spacing when estimating available row width.

Summary

  • Measure text with real font metrics and consistent padding.
  • Return dynamic sizes in flow layout delegate methods.
  • Cache widths for performance on stable data sets.
  • Test dynamic type and localization edge cases early.

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.