Skip to main content

About this widget

Displays the highlighted attributes of your search results.

Examples

Consider a movies index. Each movie record consists of two fields: title and year. Algolia’s response to the query “red” could look like:
JSON
{
  "title": "The Shawshank Redemption",
  "year": 1994,
  "objectID": "439817390",
  "_highlightResult": {
    "title": {
      "value": "The Shawshank <em>Red</em>emption",
      "matchLevel": "full",
      "fullyHighlighted": false,
      "matchedWords": ["red"]
    }
  }
}
Consider 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.
Swift
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.
Swift
let attributedString: NSAttributedString = ...
let label: UILabel = ...

label.attributedText = attributedString
The Hit wrapper structure uses the HighlightedString structure. You can extract a highlighted string for an attribute using its hightlightedString(forKey key: String) function. Example:
Swift
/* JSON search response
  {
    "title": "The Shawshank Redemption",
    "year": 1994,
    "objectID": "439817390",
    "_highlightResult": {
      "title": {
        "value": "The Shawshank <em>Red</em>emption",
        "matchLevel": "full",
        "fullyHighlighted": false,
        "matchedWords": [
          "red"
        ]
      },
    }
  }
*/

struct Movie: Codable {
  let title: String
  let year: Int
}

let movieHit: Hit<Movie> = ... /* parse JSON response */

let highlightedMovieTitle: HighlightedString? = movieHit.hightlightedString(forKey: "title")
You can read more about usage of the Hit wrapper structure in the Hits reference.
I