UILabel
UIToolbar
iOS Development
Swift
User Interface

Adding a UILabel to a UIToolbar

Master System Design with Codemia

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

Introduction

In iOS development, UIToolbar is a common component for presenting actions at the bottom of the screen. It is designed to hold UIBarButtonItem instances, which means adding a plain UILabel requires a small workaround. The key insight is that UIBarButtonItem supports a customView initializer, so you can wrap any UIView (including a UILabel) inside a bar button item and place it in the toolbar. This article walks through the full process with working Swift code, layout tips, and common mistakes to avoid.

Setting Up the Toolbar Programmatically

The first step is creating a UIToolbar and adding it to your view controller's view hierarchy. You can do this in viewDidLoad or wherever you configure your UI.

swift
1override func viewDidLoad() {
2    super.viewDidLoad()
3
4    let toolbar = UIToolbar()
5    toolbar.translatesAutoresizingMaskIntoConstraints = false
6    view.addSubview(toolbar)
7
8    NSLayoutConstraint.activate([
9        toolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
10        toolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
11        toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
12        toolbar.heightAnchor.constraint(equalToConstant: 44)
13    ])
14}

Using Auto Layout here ensures the toolbar resizes correctly across different screen sizes and orientations. You could also set the frame manually, but constraints are the recommended approach in modern iOS development.

Creating a UILabel as a Bar Button Item

Once the toolbar is in place, you create a UILabel, configure its appearance, and wrap it inside a UIBarButtonItem using the customView parameter.

swift
1let statusLabel = UILabel()
2statusLabel.text = "3 items selected"
3statusLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
4statusLabel.textColor = .darkGray
5statusLabel.textAlignment = .center
6statusLabel.sizeToFit()
7
8let labelItem = UIBarButtonItem(customView: statusLabel)

Calling sizeToFit() is important because it tells the label to calculate its intrinsic content size based on the current text and font. Without this call, the label may appear with zero width and be invisible in the toolbar.

Centering the Label with Flexible Spaces

To center the label inside the toolbar, place UIBarButtonItem.flexibleSpace() items on both sides. Flexible spaces expand to fill available room, which pushes the label to the center.

swift
1let flexLeft = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
2let flexRight = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
3
4toolbar.setItems([flexLeft, labelItem, flexRight], animated: false)

If you want the label aligned to the left, drop the leading flexible space. For right alignment, drop the trailing one. You can also mix the label with actual buttons for more complex layouts.

Combining the Label with Action Buttons

A realistic toolbar often combines a label with action buttons. For example, a selection toolbar might show the count of selected items alongside a "Delete" button.

swift
1let deleteButton = UIBarButtonItem(
2    title: "Delete",
3    style: .plain,
4    target: self,
5    action: #selector(deleteSelected)
6)
7deleteButton.tintColor = .systemRed
8
9let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
10
11toolbar.setItems([labelItem, flex, deleteButton], animated: false)

This places the label on the left and the delete button on the right, which is a common pattern in apps like Mail and Photos.

Updating the Label Dynamically

Since you hold a reference to the UILabel instance, you can update its text at any time. The toolbar will reflect changes immediately.

swift
1func updateSelectionCount(_ count: Int) {
2    statusLabel.text = "\(count) items selected"
3    statusLabel.sizeToFit()
4}

Call sizeToFit() again after changing the text so the label resizes to fit the new content. If you are using Auto Layout constraints on the label instead, this step is not necessary because the intrinsic content size updates automatically.

Using a UILabel in a Storyboard Toolbar

If you are working with Interface Builder, you cannot drag a UILabel directly into a toolbar. Instead, add a UIBarButtonItem, then in your view controller's code, replace it with a custom view version.

swift
1@IBOutlet weak var toolbar: UIToolbar!
2
3override func viewDidLoad() {
4    super.viewDidLoad()
5
6    let label = UILabel()
7    label.text = "Ready"
8    label.font = UIFont.preferredFont(forTextStyle: .footnote)
9    label.sizeToFit()
10
11    let labelItem = UIBarButtonItem(customView: label)
12    let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
13
14    toolbar.items = [flex, labelItem, flex]
15}

Common Pitfalls

Forgetting sizeToFit(). The most frequent mistake is skipping sizeToFit() after creating or updating the label. The label defaults to zero size, so it will be invisible in the toolbar even though it exists in the item array.

Using fixedSpace instead of flexibleSpace. Fixed spaces have a set width and will not adapt to different screen sizes. Always use flexible spaces for dynamic centering.

Not updating after text changes. If you change statusLabel.text but do not call sizeToFit(), the label may truncate or overflow. Consider setting adjustsFontSizeToFitWidth to true as a safety net for unexpectedly long strings.

Ignoring safe areas. On devices with a home indicator (iPhone X and later), make sure the toolbar is constrained to safeAreaLayoutGuide.bottomAnchor rather than the view's bottom edge. Otherwise the toolbar will be partially hidden behind the home indicator.

Summary

Adding a UILabel to a UIToolbar is straightforward once you understand the UIBarButtonItem(customView:) pattern. Create your label, wrap it in a bar button item, and use flexible spaces to control its position. Remember to call sizeToFit() whenever the text changes, and use Auto Layout to keep the toolbar properly positioned across all device sizes. This technique works for any custom view, not just labels, so you can apply the same approach to add progress indicators, switches, or segmented controls to a toolbar.


Course illustration
Course illustration

All Rights Reserved.