Underline Text in UILabel: Multi-Line and Partial Ranges

Underline Text in UILabel: Multi-Line and Partial Ranges

Written by

in

Quick answer: Set the label’s attributedText to an NSAttributedString whose attributes include .underlineStyle: NSUnderlineStyle.single.rawValue. That underlines every line of a multi-line label automatically, and you can underline just part of the string by adding the attribute to a specific NSRange.

Why this happens

UILabel has no underline property. Font, color and decorations are not properties of the label — they belong to the text, which is why the supported way to underline is an NSAttributedString carrying the .underlineStyle attribute. Since iOS 6 UILabel renders attributed text directly, so no subclass is needed.

The older workaround — subclassing UILabel and stroking a line in drawRect(_:) — draws one straight line across the label’s bounds. It ignores line wrapping, text alignment and the label’s insets, so it looks like a bottom border rather than an underline, and it falls apart the moment the text is centered or wraps.

The original plan of using textRectForBounds(_:limitedToNumberOfLines:) can’t work either: that method returns a single rectangle for the whole text block. It does not expose per-line fragments, so there is no start point or length to read for each line.

How to fix it

1. Set an attributed string with .underlineStyle

import UIKit

final class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let label = UILabel()
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)

        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
            label.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
            label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40)
        ])

        label.attributedText = NSAttributedString(
            string: "This sentence is underlined and wraps onto as many lines as it needs.",
            attributes: [
                .font: UIFont.preferredFont(forTextStyle: .body),
                .foregroundColor: UIColor.label,
                .underlineStyle: NSUnderlineStyle.single.rawValue
            ]
        )
    }
}

Two details matter. The value for .underlineStyle is an Int — the rawValue of NSUnderlineStyle — not the option set itself. And numberOfLines must be 0 (or greater than one) if wrapped lines should be underlined too; each line fragment gets its own underline automatically.

NSUnderlineStyle is an option set, so styles can be combined:

// double line
.underlineStyle: NSUnderlineStyle.double.rawValue

// dashed single line
.underlineStyle: NSUnderlineStyle.single.union(.patternDash).rawValue

2. Underline only part of the text

let text = "By continuing you accept the terms of service."
let attributed = NSMutableAttributedString(
    string: text,
    attributes: [.font: UIFont.preferredFont(forTextStyle: .body)]
)

let range = (text as NSString).range(of: "terms of service")
attributed.addAttribute(.underlineStyle,
                        value: NSUnderlineStyle.single.rawValue,
                        range: range)

label.attributedText = attributed

Use NSString ranges here. addAttribute(_:value:range:) takes an NSRange, and converting a Range<String.Index> back and forth is easy to get wrong with emoji or composed characters.

3. Control the underline color and keep the rest of the styling

let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
paragraph.lineSpacing = 4

let attributes: [NSAttributedString.Key: Any] = [
    .font: UIFont.preferredFont(forTextStyle: .body),
    .foregroundColor: UIColor.label,
    .underlineColor: UIColor.systemOrange,
    .underlineStyle: NSUnderlineStyle.single.rawValue,
    .paragraphStyle: paragraph
]

label.attributedText = NSAttributedString(
    string: "Centered, underlined, orange line.",
    attributes: attributes
)

Once attributedText is set, put font, color and alignment in the attributes instead of relying on label.font, label.textColor and label.textAlignment. The appearance then lives in one place and survives reuse of the label.

4. Reuse it with a small extension

extension UILabel {
    func setUnderlinedText(_ text: String, color: UIColor = .label) {
        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = textAlignment
        paragraph.lineBreakMode = lineBreakMode

        let resolvedFont = font ?? UIFont.preferredFont(forTextStyle: .body)

        attributedText = NSAttributedString(
            string: text,
            attributes: [
                .font: resolvedFont,
                .foregroundColor: color,
                .underlineStyle: NSUnderlineStyle.single.rawValue,
                .paragraphStyle: paragraph
            ]
        )
    }
}

5. If you need underlines the attribute can’t express

For a hand-drawn or offset underline, drop to TextKit: build an NSTextStorage, NSLayoutManager and NSTextContainer, then use enumerateLineFragments(forGlyphRange:) to get each line’s rectangle before drawing. That is a lot of machinery for a decoration — for anything a normal label shows, the attribute is the right tool. Third-party labels such as TTTAttributedLabel existed because UILabel had no attributed text before iOS 6; today they only make sense when you also need tap handling on ranges.

How to prevent it

  • Never draw underlines in drawRect(_:) on a UILabel subclass — the line cannot follow wrapped or centered text.
  • Pass NSUnderlineStyle.single.rawValue, not NSUnderlineStyle.single, as the attribute value.
  • Set numberOfLines = 0 before expecting multi-line underlines.
  • Don’t assign label.text after label.attributedText — it replaces the attributed string and drops the underline.
  • Keep attribute dictionaries in one helper so font, color and underline stay consistent across labels.

FAQ

Does .underlineStyle work on a multi-line UILabel?

Yes. Every line fragment is underlined, including lines produced by wrapping, as long as numberOfLines allows more than one line. You don’t need to compute line ranges or start points yourself.

Why is my underline missing after I set the text?

The usual cause is assigning label.text = "..." after label.attributedText, which replaces the attributed string. The second cause is passing the NSUnderlineStyle value instead of its rawValue, which the text system ignores.

Can I underline a link inside a label and make it tappable?

UILabel does not deliver taps on ranges. Underline the range with .underlineStyle for appearance, and use a non-editable, selectable UITextView if the link must actually respond to taps. In SwiftUI, Text("...").underline() covers the simple case.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.