UILabel
Swift
Centering
iOS Development
SwiftUI

How to center UILabel in Swift?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To center a UILabel in its superview in UIKit, use Auto Layout constraints to pin its centerXAnchor and centerYAnchor to the superview's corresponding anchors. In Interface Builder, select the label and add "Horizontally in Container" and "Vertically in Container" constraints. In SwiftUI, views are centered by default within their parent container. The key requirement in programmatic UIKit is setting translatesAutoresizingMaskIntoConstraints = false before adding constraints, otherwise the autoresizing mask conflicts with Auto Layout.

Programmatic Auto Layout (UIKit)

swift
1import UIKit
2
3class ViewController: UIViewController {
4    override func viewDidLoad() {
5        super.viewDidLoad()
6
7        let label = UILabel()
8        label.text = "Hello, World!"
9        label.textAlignment = .center
10        label.translatesAutoresizingMaskIntoConstraints = false
11
12        view.addSubview(label)
13
14        NSLayoutConstraint.activate([
15            label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
16            label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
17        ])
18    }
19}

translatesAutoresizingMaskIntoConstraints = false tells UIKit to use Auto Layout constraints instead of the legacy autoresizing mask. Without this, the constraints conflict with auto-generated ones and the label does not center correctly.

Centering Within a Specific Area

swift
1// Center horizontally but position vertically at 1/3 from top
2NSLayoutConstraint.activate([
3    label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
4    label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100)
5])
6
7// Center within a container view (not the full screen)
8let container = UIView()
9container.translatesAutoresizingMaskIntoConstraints = false
10view.addSubview(container)
11
12// Set up container constraints first
13NSLayoutConstraint.activate([
14    container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
15    container.leadingAnchor.constraint(equalTo: view.leadingAnchor),
16    container.trailingAnchor.constraint(equalTo: view.trailingAnchor),
17    container.heightAnchor.constraint(equalToConstant: 200)
18])
19
20// Then center label within the container
21container.addSubview(label)
22NSLayoutConstraint.activate([
23    label.centerXAnchor.constraint(equalTo: container.centerXAnchor),
24    label.centerYAnchor.constraint(equalTo: container.centerYAnchor)
25])

Centering Text Within the Label

swift
1// textAlignment centers the TEXT within the label's frame
2label.textAlignment = .center
3
4// For a label with a fixed width, this matters:
5NSLayoutConstraint.activate([
6    label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
7    label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
8    label.widthAnchor.constraint(equalToConstant: 300)  // Fixed width
9])
10// textAlignment = .center ensures text is centered within the 300pt width
11
12// For multi-line labels
13label.numberOfLines = 0  // Unlimited lines
14label.textAlignment = .center
15label.lineBreakMode = .byWordWrapping
16
17NSLayoutConstraint.activate([
18    label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
19    label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
20    label.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 20),
21    label.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20)
22])

textAlignment controls how text is aligned within the label's bounds. centerXAnchor/centerYAnchor controls where the label itself is positioned within its superview. Both are needed for fully centered text on screen.

Interface Builder / Storyboard

swift
1// In Interface Builder:
2// 1. Drag a UILabel onto the view
3// 2. Select the label
4// 3. Click the "Align" button (bottom of canvas)
5// 4. Check "Horizontally in Container" and "Vertically in Container"
6// 5. Click "Add 2 Constraints"
7
8// Or use Control-drag:
9// 1. Control-drag from label to the superview
10// 2. Select "Center Horizontally in Safe Area"
11// 3. Control-drag again, select "Center Vertically in Safe Area"
12
13// Via the Size Inspector, verify:
14// - Align Center X to: Safe Area
15// - Align Center Y to: Safe Area

Interface Builder generates the same NSLayoutConstraint code as the programmatic approach. Use the Document Outline panel to verify constraints are attached to the correct views.

Using UIStackView for Centering

swift
1let stackView = UIStackView()
2stackView.axis = .vertical
3stackView.alignment = .center       // Centers children horizontally
4stackView.distribution = .fill
5stackView.translatesAutoresizingMaskIntoConstraints = false
6
7let label = UILabel()
8label.text = "Centered via StackView"
9stackView.addArrangedSubview(label)
10
11view.addSubview(stackView)
12
13NSLayoutConstraint.activate([
14    stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
15    stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
16])

UIStackView with .alignment = .center centers all arranged subviews along the cross axis. This is useful when centering multiple labels or a group of views.

SwiftUI Centering

swift
1import SwiftUI
2
3// Views are centered by default in SwiftUI
4struct ContentView: View {
5    var body: some View {
6        Text("Hello, World!")
7            // Already centered in the available space
8    }
9}
10
11// Explicit centering with frame
12struct ExplicitCenterView: View {
13    var body: some View {
14        Text("Centered")
15            .frame(maxWidth: .infinity, maxHeight: .infinity)
16            .background(Color.gray.opacity(0.2))
17    }
18}
19
20// Center within a specific area
21struct PartialCenterView: View {
22    var body: some View {
23        VStack {
24            Text("Centered in top half")
25                .frame(maxWidth: .infinity, maxHeight: .infinity)
26            Spacer()
27        }
28        .frame(height: 300)
29    }
30}

In SwiftUI, Text views are centered within their parent by default. Use .frame(maxWidth: .infinity, maxHeight: .infinity) to expand the view to fill available space and center within it.

Common Pitfalls

  • Forgetting translatesAutoresizingMaskIntoConstraints = false: Without this, the view's autoresizing mask creates conflicting constraints. Auto Layout logs ambiguous layout warnings, and the label does not position correctly. Always set this to false for programmatic constraints.
  • Adding constraints before adding the subview: Constraints reference the view hierarchy. If you activate constraints before calling addSubview(), the app crashes with "Unable to activate constraint with anchors...not a common ancestor." Always add the subview first.
  • Centering text vs centering the label: textAlignment = .center centers text within the label's frame. If the label itself is left-aligned in the superview, the text appears off-center on screen. You need both textAlignment and centering constraints.
  • Not using safeAreaLayoutGuide for vertical centering: On devices with notches or home indicators, centering relative to view.centerYAnchor may appear visually off-center because the safe area is not symmetric. Use view.safeAreaLayoutGuide.centerYAnchor for a visually balanced position.
  • Conflicting width constraints with centering: Adding both leading/trailing constraints and a centerX constraint can cause conflicts. Use either leading+trailing (for full-width labels) or centerX+width (for fixed-width labels), not both simultaneously.

Summary

  • Use centerXAnchor and centerYAnchor constraints to center a UILabel programmatically
  • Always set translatesAutoresizingMaskIntoConstraints = false before adding constraints
  • Set textAlignment = .center to center text within the label's bounds
  • In Interface Builder, use "Horizontally in Container" and "Vertically in Container" alignment constraints
  • Use UIStackView with .alignment = .center to center groups of views
  • In SwiftUI, Text is centered by default; use .frame(maxWidth: .infinity) for explicit full-space centering

Course illustration
Course illustration

All Rights Reserved.