Swift
UILabel
iOS Development
Programmatically
SwiftUI

How to create UILabel programmatically using Swift?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Creating a UILabel programmatically is useful for dynamic layouts, reusable components, and screens not built in Interface Builder. The core steps are creating the label, configuring text style, and adding constraints. A clean pattern also supports accessibility and dynamic type from the start.

Core Sections

Create and Configure a Basic Label

Start with explicit style properties so defaults do not surprise you later.

swift
1import UIKit
2
3let titleLabel = UILabel()
4titleLabel.text = "Welcome"
5titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .semibold)
6titleLabel.textColor = .label
7titleLabel.textAlignment = .center
8titleLabel.numberOfLines = 0
9titleLabel.translatesAutoresizingMaskIntoConstraints = false

Setting numberOfLines to zero allows wrapping for longer localized text.

Add Label to View with Auto Layout

Add the label to a parent view and apply constraints.

swift
1class WelcomeViewController: UIViewController {
2    private let titleLabel: UILabel = {
3        let label = UILabel()
4        label.text = "Welcome to the app"
5        label.font = UIFont.systemFont(ofSize: 24, weight: .bold)
6        label.textAlignment = .center
7        label.numberOfLines = 0
8        label.translatesAutoresizingMaskIntoConstraints = false
9        return label
10    }()
11
12    override func viewDidLoad() {
13        super.viewDidLoad()
14        view.backgroundColor = .systemBackground
15        view.addSubview(titleLabel)
16
17        NSLayoutConstraint.activate([
18            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
19            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
20            titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 32)
21        ])
22    }
23}

This is the most common UIKit programmatic setup style.

Build Reusable Label Factory

If several screens share typography rules, build a helper.

swift
1func makeSectionLabel(_ text: String) -> UILabel {
2    let label = UILabel()
3    label.text = text
4    label.font = UIFont.preferredFont(forTextStyle: .headline)
5    label.adjustsFontForContentSizeCategory = true
6    label.textColor = .secondaryLabel
7    label.translatesAutoresizingMaskIntoConstraints = false
8    return label
9}

Factories improve consistency and reduce copy-paste style drift.

Support Dynamic Type and Accessibility

Programmatic UI should include accessibility properties, not only visual styles.

swift
1titleLabel.adjustsFontForContentSizeCategory = true
2titleLabel.isAccessibilityElement = true
3titleLabel.accessibilityTraits = .header
4titleLabel.accessibilityLabel = "Welcome to the app"

This improves usability for larger text sizes and screen readers.

Update Label Text Safely on Background Work

If label content comes from async operations, ensure UI updates run on main thread.

swift
1Task {
2    let message = await fetchWelcomeMessage()
3    await MainActor.run {
4        self.titleLabel.text = message
5    }
6}

UIKit updates off main thread can cause unpredictable behavior.

Advanced Styling with Attributed Text

For mixed styles in one label, use attributed strings.

swift
let styled = NSMutableAttributedString(string: "Score: 98")
styled.addAttributes([.font: UIFont.boldSystemFont(ofSize: 22)], range: NSRange(location: 7, length: 2))
titleLabel.attributedText = styled

Keep range calculations dynamic when localized strings vary.

Integrate Labels into Stack-based Layouts

Most real screens contain multiple labels and controls. UIStackView works well with programmatically created labels and keeps constraints manageable.

swift
1let subtitleLabel = UILabel()
2subtitleLabel.text = "Sign in to continue"
3subtitleLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
4subtitleLabel.textColor = .secondaryLabel
5subtitleLabel.numberOfLines = 0
6
7let stack = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel])
8stack.axis = .vertical
9stack.spacing = 8
10stack.translatesAutoresizingMaskIntoConstraints = false
11
12view.addSubview(stack)
13NSLayoutConstraint.activate([
14    stack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
15    stack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
16    stack.centerYAnchor.constraint(equalTo: view.centerYAnchor)
17])

Stack-based composition makes dynamic text and localization more resilient because views can grow naturally without brittle manual frame math.

For large UIKit codebases, defining a lightweight typography system for programmatic labels improves consistency and significantly reduces design drift over time. It also makes theme updates faster.

Performance and Reuse Notes

Programmatic labels are lightweight, but repeated setup in scrolling lists should still be optimized through reuse. In table and collection cells, configure text and style once in setup, then update only data values during reuse. This avoids unnecessary layout churn and keeps scrolling smooth on older devices.

When loading remote content, prefer placeholder text plus progressive updates rather than repeatedly removing and recreating labels. Stable view hierarchies are easier to animate and debug.

Common Pitfalls

  • Forgetting translatesAutoresizingMaskIntoConstraints equals false before adding constraints.
  • Hardcoding frames and then mixing with Auto Layout constraints.
  • Ignoring dynamic type, causing text clipping on larger accessibility sizes.
  • Updating label text from background threads.
  • Duplicating style setup across files instead of reusing helper functions.

Summary

  • Create labels programmatically with explicit style and layout settings.
  • Use Auto Layout constraints for predictable positioning.
  • Build reusable label helpers for consistent typography.
  • Include accessibility and dynamic type support by default.
  • Keep async UI updates on main thread for correctness.

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.