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.
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:
- Build a text container that matches label width and line settings.
- Feed it with the same attributed text.
- Convert substring character range to glyph range.
- 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.
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.
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.
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
lineBreakModeandnumberOfLinesin 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
UILabeldoes 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.
Related reading
- How do I make a custom initializer for a UIViewController subclass in Swift?
- How do I make a dotted/dashed line in Android?
- How do I make a new line in swift
- How do I make an attributed string using Swift?
- How do I make an enum Decodable in Swift?
- How do I make UILabel display outlined text?
- How do I make WRAP_CONTENT work on a RecyclerView
- How do I modify the background color of a List in SwiftUI?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.