API Reference / iOS InstantSearch Widgets / Highlighting
Apr. 24, 2019

Highlighting

About this widget

HighlightedString simplifies highlighting the words in a search response that match your query.
You can read more about the concept of highlighting in our highlighting guide.

Examples

Lets take the example of an index containing movies. Each movie record consists of two fields: title and year. Here is what the search engine response for a query "red" could look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    {
    "title": "The Shawshank Redemption",
    "year": 1994,
    "objectID": "439817390",
    "_highlightResult": {
      "title": {
        "value": "The Shawshank <em>Red</em>emption",
        "matchLevel": "full",
        "fullyHighlighted": false,
        "matchedWords": [
          "red"
        ]
      },
    }
  },

We are interested in the _highlightResult’s value: "The Shawshank <em>Red</em>emption". The part of the string to highlight is marked with <em> tags or your custom tags.

HighlightedString is constructed with a raw tagged string, detects the tags and creates a TaggedString.
This tagged string provides following properties:

  • input: the input string.
  • output: the input string without its tags.
  • taggedRanges: a list of ranges defining highlighted ranges in output.

You can build a highlighted string in iOS is with an NSAttributedString. InstantSearch provides HighlightedString and NSAttributedString extensions to make this easy.

1
2
3
4
5
6
7
8
9
10
  let rawHighlightedString = "The Shawshank <em>Red</em>emption"
  let highlightedString = HighlightedString(string: rawHighlightedString)

  // Attributes to apply for a highlighted part of the string
  let highLightingAttributes: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.red
  ]

  // Create attributed string highlighted part of which is red
  let attributedString = NSAttributedString(highlightedString: highlightedString, attributes: attributes)

The produced NSAttributedString can be assigned to a UIKit component that supports it.

1
2
3
4
  let attributedString: NSAttributedString = ...
  let label: UILabel = ...

  label.attributedText = attributedString

HighlightedString is widely used in the Hit wrapper structure. You can read more about it in the Hits documentation.

Did you find this page helpful?