UILabel
iOS Development
Underlined Text
Swift Programming
User Interface Design

Underline text in UIlabel

Master System Design with Codemia

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

Introduction

UILabel does not support underline styling through the plain text property. Underlines are applied with attributed strings, which gives precise control over style, color, and range. A clean implementation should also handle reuse, localization, and accessibility so formatting remains correct as text changes.

Apply Full Underline With Attributed Text

The simplest case is underlining the entire label string.

swift
1import UIKit
2
3func applyFullUnderline(to label: UILabel, text: String) {
4    let attributes: [NSAttributedString.Key: Any] = [
5        .underlineStyle: NSUnderlineStyle.single.rawValue,
6        .foregroundColor: UIColor.systemBlue
7    ]
8
9    label.attributedText = NSAttributedString(string: text, attributes: attributes)
10}

Use this when the whole label should be link-like or emphasized.

Underline Only Part of a String

Most UI needs partial underline such as “Read privacy policy” where only one phrase is underlined.

swift
1import UIKit
2
3func applyPartialUnderline(to label: UILabel) {
4    let text = "Read privacy policy"
5    let attributed = NSMutableAttributedString(string: text)
6
7    let nsText = text as NSString
8    let range = nsText.range(of: "privacy policy")
9
10    if range.location != NSNotFound {
11        attributed.addAttributes([
12            .underlineStyle: NSUnderlineStyle.single.rawValue,
13            .foregroundColor: UIColor.systemBlue
14        ], range: range)
15    }
16
17    label.attributedText = attributed
18}

Using NSString range APIs avoids mistakes with Unicode indexing in many practical cases.

Preserve Existing Attributes While Updating Text

If labels already have fonts or colors assigned via attributed text, replacing everything can drop styles accidentally. Merge attributes carefully.

swift
1func updateUnderlinePreservingStyle(label: UILabel, term: String) {
2    let baseText = label.text ?? ""
3    let attributed = NSMutableAttributedString(string: baseText, attributes: [
4        .font: label.font as Any,
5        .foregroundColor: label.textColor as Any
6    ])
7
8    let range = (baseText as NSString).range(of: term)
9    if range.location != NSNotFound {
10        attributed.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
11    }
12
13    label.attributedText = attributed
14}

This pattern prevents style regressions when UI state updates frequently.

Reusable Extension for Teams

Centralize underline logic to avoid duplicate formatting code across view controllers.

swift
1import UIKit
2
3extension UILabel {
4    func setUnderlinedText(_ text: String,
5                           color: UIColor = .label,
6                           style: NSUnderlineStyle = .single) {
7        let attrs: [NSAttributedString.Key: Any] = [
8            .underlineStyle: style.rawValue,
9            .foregroundColor: color,
10            .font: font as Any
11        ]
12        attributedText = NSAttributedString(string: text, attributes: attrs)
13    }
14}

With one helper, style changes become easier to enforce consistently.

Handle Dynamic Type and Reuse

In table or collection views, labels are reused. Always set attributed text in configure methods so old underline state does not leak to new content.

swift
1final class TermsCell: UITableViewCell {
2    @IBOutlet private weak var titleLabel: UILabel!
3
4    func configure(title: String, isLink: Bool) {
5        if isLink {
6            titleLabel.setUnderlinedText(title, color: .systemBlue)
7        } else {
8            titleLabel.attributedText = NSAttributedString(string: title, attributes: [
9                .font: titleLabel.font as Any,
10                .foregroundColor: UIColor.label
11            ])
12        }
13    }
14}

This avoids reused-cell artifacts where unrelated rows appear underlined.

Accessibility and Design Guidance

Underline often implies tappable content. If text is interactive, pair underline with traits and hit targets that communicate intent clearly. Do not rely on color alone to indicate link behavior. In high-contrast settings, verify underline remains visible and text remains legible.

If label text changes from localization, re-run range calculations on localized strings rather than assuming fixed English indices.

When underline indicates a tap action, pair label styling with gesture or button wrappers so interaction behavior matches visual expectations.

Common Pitfalls

A common pitfall is assigning label.text after attributedText, which removes underline formatting immediately. Another issue is computing ranges with hard-coded index offsets that break under localization. Teams also forget to reset attributed text in reusable cells, causing stale formatting. Underline color confusion is common as well, since underline follows text color unless explicitly configured in styled rendering contexts. Finally, accessibility can suffer when underline is used as the only signal for interactive content without proper traits.

Summary

  • Underline in UILabel requires attributed strings, not plain text.
  • Use full or partial underline based on UX needs.
  • Preserve existing style attributes when updating dynamic content.
  • Centralize formatting logic with a reusable extension.
  • Validate reuse, localization, and accessibility to keep underline behavior reliable.

Course illustration
Course illustration

All Rights Reserved.