iOS development
UILabel
Swift programming
text rendering
CGRect calculation

How do I locate the CGRect for a substring of text in a UILabel?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Finding the exact rectangle of a substring inside a UILabel is a common need for tappable links, inline highlights, tooltips, and annotation overlays. The challenge is that UILabel does not expose glyph-level geometry directly. The practical solution is to recreate the label layout using TextKit, then ask the layout manager for the substring bounds.

Why UILabel Alone Is Not Enough

UILabel renders text internally, but it does not provide APIs like “give me the frame of characters 10 through 20.” Methods such as sizeThatFits only return overall size, not per-substring rectangles. If you try to estimate with string widths manually, results drift on line wraps, kerning, dynamic type, and paragraph styles.

So the robust approach is:

  1. Build a text container that matches label width and line settings.
  2. Feed it with the same attributed text.
  3. Convert substring character range to glyph range.
  4. Ask TextKit for glyph bounding rectangle in label coordinates.

Rebuild Label Layout With TextKit

This implementation mirrors core label settings and returns one rectangle for the first match.

swift
1import UIKit
2
3func substringRect(in label: UILabel, substring: String) -> CGRect? {
4    guard let fullText = label.attributedText?.string ?? label.text,
5          let swiftRange = fullText.range(of: substring) else {
6        return nil
7    }
8
9    let attributed = label.attributedText ?? NSAttributedString(
10        string: fullText,
11        attributes: [
12            .font: label.font as Any,
13            .foregroundColor: label.textColor as Any
14        ]
15    )
16
17    let textStorage = NSTextStorage(attributedString: attributed)
18    let layoutManager = NSLayoutManager()
19    let textContainer = NSTextContainer(size: label.bounds.size)
20
21    textContainer.lineFragmentPadding = 0
22    textContainer.maximumNumberOfLines = label.numberOfLines
23    textContainer.lineBreakMode = label.lineBreakMode
24
25    layoutManager.addTextContainer(textContainer)
26    textStorage.addLayoutManager(layoutManager)
27
28    let nsRange = NSRange(swiftRange, in: fullText)
29    let glyphRange = layoutManager.glyphRange(forCharacterRange: nsRange, actualCharacterRange: nil)
30
31    var rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
32
33    // Convert from container coordinates to label coordinates.
34    let used = layoutManager.usedRect(for: textContainer)
35    let xOffset = (label.bounds.width - used.width) * 0.5 - used.minX
36    let yOffset = (label.bounds.height - used.height) * 0.5 - used.minY
37
38    rect.origin.x += xOffset
39    rect.origin.y += yOffset
40
41    return rect.integral
42}

For most centered labels this gives the correct hit area directly.

Handle Wrapped Substrings and Multiple Matches

A substring can span more than one line. In that case, a single rectangle may be too broad or inaccurate for highlighting. You can enumerate line fragments in the glyph range and return one rectangle per line fragment.

swift
1func substringRects(in label: UILabel, ranges: [NSRange]) -> [CGRect] {
2    guard let attributed = label.attributedText else { return [] }
3
4    let textStorage = NSTextStorage(attributedString: attributed)
5    let layoutManager = NSLayoutManager()
6    let textContainer = NSTextContainer(size: label.bounds.size)
7
8    textContainer.lineFragmentPadding = 0
9    textContainer.maximumNumberOfLines = label.numberOfLines
10    textContainer.lineBreakMode = label.lineBreakMode
11
12    layoutManager.addTextContainer(textContainer)
13    textStorage.addLayoutManager(layoutManager)
14
15    var rects: [CGRect] = []
16
17    for range in ranges {
18        let glyphRange = layoutManager.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
19
20        layoutManager.enumerateLineFragments(forGlyphRange: glyphRange) { _, usedRect, _, fragmentGlyphRange, _ in
21            let intersection = NSIntersectionRange(fragmentGlyphRange, glyphRange)
22            guard intersection.length > 0 else { return }
23            let lineRect = layoutManager.boundingRect(forGlyphRange: intersection, in: textContainer)
24            rects.append(lineRect)
25        }
26    }
27
28    return rects.map { $0.integral }
29}

This is better for drawing exact highlight backgrounds behind wrapped link text.

Tap Detection Pattern

Once you have a substring rect, tap handling is straightforward.

swift
1@objc func didTapLabel(_ gesture: UITapGestureRecognizer) {
2    guard let label = gesture.view as? UILabel else { return }
3    let point = gesture.location(in: label)
4
5    if let rect = substringRect(in: label, substring: "Terms"), rect.contains(point) {
6        print("Terms tapped")
7    }
8}

For production UI, compare against an array of rectangles and identifiers, then route to matching action.

Accuracy and Timing Notes

Run geometry calculations after Auto Layout resolves final bounds, usually in viewDidLayoutSubviews or after layoutIfNeeded. If you compute too early, label width can still be zero or stale, producing wrong rectangles.

Also ensure text attributes match rendered output. If label text uses custom kerning, paragraph style, or attributed spans, those must be present in the NSTextStorage input. Mismatch here is the most common source of off-by-pixels hit areas.

For repeated hit testing, cache layout artifacts instead of recreating TextKit objects for every tap.

Common Pitfalls

  • Estimating substring position with plain string-width math instead of using TextKit layout data.
  • Computing rectangles before Auto Layout finishes, which produces stale or zero-width bounds.
  • Forgetting to mirror label settings such as lineBreakMode and numberOfLines in the text container.
  • Assuming every substring maps to one rectangle, even when the text wraps across multiple lines.
  • Ignoring attributed styling differences, which causes geometry drift on mixed fonts, emoji, or multilingual text.

Summary

  • UILabel does not provide direct substring geometry APIs.
  • Recreate layout with TextKit using the same text and line settings.
  • Convert character ranges to glyph ranges and request bounding rectangles.
  • Use per-line fragment rectangles when substrings wrap.
  • Compute after layout and keep attributes synchronized for accurate tap and highlight behavior.

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
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms