skip to content

In a SwiftUI search screen, how do you highlight the matched part of each merchant name with AttributedString when Markdown and Text modifiers cannot express it?

level: seniorimportance: should knowfreq 35%

answer

  1. a range, not a whole string
  2. SwiftUI's attribute scope
  3. attributes beat modifiers
  4. build it once, outside body

basics

~20 s

Wrap the merchant name in an AttributedString, find the match with range(of:options:), set attributes such as backgroundColor and font on that range, and pass it to Text. Text draws SwiftUI's attributes per run, and a run's attributes win over modifiers.

solid answer

~40 s

Markdown is fixed at authoring time and Text modifiers style the whole `Text`, so a highlight that depends on the user's query needs an `AttributedString`. Build it from the name, find the match with `range(of: query, options: [.caseInsensitive, .diacriticInsensitive])`, and assign through the range: `text[range].backgroundColor = .yellow` and `text[range].font = .body.bold()`. `Text(attributed)` (iOS 15) draws each run with its attributes: SwiftUI's scope includes `font`, `foregroundColor`, `backgroundColor`, `strikethroughStyle`, `underlineStyle`, `kern`, `tracking` and `baselineOffset`, and Foundation's `link` works too. Apple's documentation says string attributes take priority over SwiftUI modifiers, so `.font(.body)` on the Text styles only the unhighlighted runs. Build the string in the model or a computed property, not with repeated parsing in `body`.

code

swift · 21 lines
swift
import SwiftUI

func highlighted(_ merchant: String, matching query: String) -> AttributedString {
    var text = AttributedString(merchant)
    guard !query.isEmpty,
          let range = text.range(of: query, options: [.caseInsensitive, .diacriticInsensitive])
    else { return text }
    text[range].backgroundColor = .yellow.opacity(0.4)
    text[range].font = .body.bold()
    return text
}

struct SearchResultRow: View {
    let merchant: String
    let query: String

    var body: some View {
        Text(highlighted(merchant, matching: query))
            .font(.body)   // the matched run's own font attribute wins over this modifier
    }
}

go deeper

for a junior

Recall that AttributedString lets one Text style part of its content, and that Text(_:) accepts it from iOS 15.

for a middle

Explain runs, assigning attributes through a range found with range(of:options:), and which SwiftUI attributes Text draws.

for a senior

Justify AttributedString over Markdown or interpolated pieces for query-driven styling, know that attributes beat modifiers, and keep the string's construction out of body in long lists.

for a principal

Decide where styled text is produced for a team, in the model or formatting layer rather than per view, so search, server Markdown and badges share one approach.

## Why Markdown and modifiers fall short The search screen shows merchants matching "café", and each row should show the matched letters highlighted: "Corner **Café** Market" with a yellow background on the match. Three tools are available, and two do not fit: - **Markdown in a literal** is fixed when the code is written; the match depends on what the user typed, and Markdown has no syntax for a background colour anyway. - **Text modifiers** such as `bold()` or `foregroundStyle(_:)` style the whole `Text`. Interpolating three `Text` pieces (before, match, after) can work, but it means slicing the string by hand and still gives no background colour. - **`AttributedString`** carries attributes on ranges of characters, called **runs**, and `Text` draws each run with its own attributes. ## Building the highlighted string 1. Create `var text = AttributedString(merchant)`. 2. Find the match: `text.range(of: query, options: [.caseInsensitive, .diacriticInsensitive])` returns a `Range<AttributedString.Index>`, so "cafe" also finds "Café". 3. Assign attributes through the range: `text[range].backgroundColor = .yellow.opacity(0.4)`, `text[range].font = .body.bold()`. 4. Show it with `Text(text)`. Each assignment splits the string into runs. Iterating `text.runs` shows them, each with a `range` and its attribute values; the matched run carries the new attributes and the others carry none. ## What Text actually draws `AttributedString` can carry attributes from several scopes. The ones to reach for in a `Text` are those SwiftUI's own scope, `AttributeScopes.SwiftUIAttributes`, declares, plus Foundation's `link`: | Attribute | Effect in Text | |---|---| | `font` | the run's font, a SwiftUI `Font` | | `foregroundColor` | the run's text colour | | `backgroundColor` | a fill behind the run's glyphs | | `strikethroughStyle`, `underlineStyle` | lines through or under the run | | `kern`, `tracking` | spacing between characters | | `baselineOffset` | raises or lowers the run | | `link` (Foundation) | a tappable link, opened through the `openURL` action | Two practical rules follow: - **Attributes win over modifiers.** Apple's documentation says you can mix string attributes and SwiftUI modifiers "with the string attributes taking priority". `.font(.body)` on the `Text` applies to runs that have no `font` attribute; the highlighted run keeps its bold. - **Use SwiftUI's types.** `backgroundColor` and `foregroundColor` here are SwiftUI `Color` values and `font` is a SwiftUI `Font`, so a run can use a text style such as `.body.bold()` rather than a point size. ## Comparing the three approaches | Approach | Styling decided | Background on part of the text | Hand slicing | |---|---|---|---| | Markdown in a literal | when the code is written | no | no | | Interpolated `Text` pieces | at runtime | no | yes, before, match and after | | `AttributedString` runs | at runtime | yes, `backgroundColor` | no, attributes go on a range | Interpolated pieces are a reasonable fallback for a bold match with no fill, but they force the code to cut the string into three and reassemble it, and a localized literal around them adds nothing for a merchant name, which is data. The attributed string keeps the name whole and puts the styling exactly where the match is. ## Where to build it `range(of:)` and attribute assignment are cheap for one name, but a list of hundreds of rows re-running them on every body evaluation adds up. Build the highlighted string where the search result is produced, or in a computed property on the row's model, so `body` only hands it to `Text`. Parsing server Markdown with `AttributedString(markdown:)` is the same idea: parse once, store the result. ## Edges worth knowing - `range(of:)` finds the **first** match; search the remaining slice, `text[hit.upperBound...]`, in a loop to highlight every occurrence. - Without `.diacriticInsensitive`, a query of "cafe" skips "Café" and matches only an unaccented spelling, which users read as a broken search. - A highlight drawn with colour alone says nothing to VoiceOver users; the matched text is still read, but if the match itself matters, say so in the row's accessibility label. - `AttributedString` is a value type, so the row's model can hold it like any other stored property. - Editing attributed text with a `TextEditor` bound to an `AttributedString` is the text-input lesson's subject; this one is about displaying it.

  • How do you highlight every occurrence of the query, not just the first?
    Loop: find a hit with `range(of:options:)`, style it, then search the slice after it, `text[hit.upperBound...]`, which is an `AttributedSubstring` with the same `range(of:options:)` and indices that are valid in the whole string. Stop when it returns `nil`. Each styled hit becomes its own run, and `Text` draws them all.
  • Why does .foregroundStyle(.secondary) on the Text not grey out a run that sets foregroundColor?
    A run's own attributes take priority over modifiers applied to the `Text`. The modifier styles runs that carry no colour; a run with `foregroundColor` keeps it. Remove the attribute from that run, or set the colour you want on the run itself.

  • Markdown can highlight a match that depends on the user's query
  • A Text modifier applied after the attributes overrides every run
  • Highlighting part of a name needs separate Text views side by side in an HStack
  • range(of:) on an AttributedString highlights all occurrences
  • Rebuilding the attributed string in body is free for long lists