UILabel
auto-size
adjust label size
iOS development
Swift programming

UILabel - auto-size label to fit text?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Auto-sizing a UILabel is mostly an Auto Layout problem, not a text rendering trick. The label needs enough constraint information to compute width and height from content. Once constraints and label properties are aligned, the system can size the label correctly for short, long, and multiline text.

How UILabel Determines Size

A label exposes an intrinsic content size based on its font, text, and line settings. Auto Layout combines that intrinsic size with constraints and priority values to pick a final frame.

For one-line labels, width is often limited by neighboring views and the label truncates if text is too long. For multiline labels, the key setting is numberOfLines = 0, which allows vertical expansion.

swift
1import UIKit
2
3let label = UILabel()
4label.text = "This is a long sentence that may wrap to multiple lines."
5label.font = .systemFont(ofSize: 17)
6label.numberOfLines = 0
7label.lineBreakMode = .byWordWrapping

If line count remains at one, the label cannot grow vertically even when constraints allow it.

Configure Auto Layout Correctly

A common pattern is pinning leading and trailing anchors and letting height be derived from content. Do not add a fixed height constraint unless your design requires clipping.

swift
1import UIKit
2
3final class AutoSizeLabelViewController: UIViewController {
4    private let titleLabel = UILabel()
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        view.backgroundColor = .systemBackground
9
10        titleLabel.translatesAutoresizingMaskIntoConstraints = false
11        titleLabel.numberOfLines = 0
12        titleLabel.font = .preferredFont(forTextStyle: .body)
13        titleLabel.text = "Auto Layout can calculate height when width is constrained and line count supports wrapping."
14
15        view.addSubview(titleLabel)
16
17        NSLayoutConstraint.activate([
18            titleLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
19            titleLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
20            titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24)
21        ])
22    }
23}

Here, width is known from leading and trailing constraints, so the system can compute wrapped height.

Use Hugging and Compression Priorities

In stacks and table cells, multiple views compete for space. Content hugging controls resistance to growing larger, while compression resistance controls resistance to shrinking.

swift
1import UIKit
2
3let title = UILabel()
4let subtitle = UILabel()
5
6title.numberOfLines = 1
7subtitle.numberOfLines = 0
8
9// Keep title from being compressed first.
10title.setContentCompressionResistancePriority(.required, for: .vertical)
11subtitle.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
12
13// Allow subtitle to expand naturally.
14subtitle.setContentHuggingPriority(.defaultLow, for: .vertical)

Priority tuning is often the difference between correct wrapping and random clipping.

Self-Sizing Labels in Table and Collection Cells

In reusable cells, automatic dimension works when constraints are complete from top to bottom of contentView. If any vertical chain is broken, cell height becomes ambiguous.

swift
1import UIKit
2
3final class MessageCell: UITableViewCell {
4    let messageLabel = UILabel()
5
6    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
7        super.init(style: style, reuseIdentifier: reuseIdentifier)
8        messageLabel.translatesAutoresizingMaskIntoConstraints = false
9        messageLabel.numberOfLines = 0
10
11        contentView.addSubview(messageLabel)
12        NSLayoutConstraint.activate([
13            messageLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
14            messageLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
15            messageLabel.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor),
16            messageLabel.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor)
17        ])
18    }
19
20    required init?(coder: NSCoder) {
21        fatalError("init(coder:) has not been implemented")
22    }
23}

With this setup and automatic row height enabled, long text expands cell height reliably.

Debugging Size Issues Quickly

When sizing still looks wrong, inspect constraints at runtime and print the label frame after layout. A reliable quick check is calling view.layoutIfNeeded() in viewDidAppear and logging final values. If the width is unexpectedly zero or tiny, the label cannot compute wrapped height correctly. In Interface Builder, ambiguous constraint warnings are often the first signal. During debugging, temporarily color the label background so clipping and truncation are visually obvious while scrolling or rotating the device.

Common Pitfalls

The most common issue is setting numberOfLines to 1 while expecting wrapping. Set it to 0 for dynamic multiline content.

Another frequent mistake is mixing fixed height constraints with automatic sizing. Fixed heights override intrinsic content and force clipping or truncation.

Ambiguous constraints inside cells also cause unstable sizes. Ensure each label has a complete vertical path inside contentView and enough horizontal constraints to determine width.

A final issue is calculating size manually while also using Auto Layout. Pick one strategy per view path, or results become inconsistent.

Summary

  • Set numberOfLines = 0 for multiline automatic height.
  • Constrain width through leading and trailing anchors.
  • Avoid unnecessary fixed height constraints.
  • Tune hugging and compression priorities in complex layouts.
  • In reusable cells, keep top-to-bottom constraints complete for self-sizing.

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.