0

I have a table view that I can search through using a search bar.

I would like to either hi-light or bold portions of text that match the string passed into the search bar.

For example, if the tableview contains: "Apple" and "Orange" and I type the letter "a", I would like the cells to now contain "Apple" and "Orange"

Through much googling I have not found a way to modify substrings of text within a table view title property.

Anyone have any idea if this is even possible?

Something like this is what I am trying to achieve in a table view:

Something like this is what I am trying to achieve

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Xaxxus
  • 1,083
  • 12
  • 19

1 Answers1

0

Please try this:

func attributedText(withString string: String, boldString: String, font: UIFont) -> NSAttributedString {
  let attributedString = NSMutableAttributedString(string: string,
                                             attributes: [NSAttributedString.Key.font: font])
  let boldFontAttribute: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: font.pointSize)]
  let range = (string as NSString).range(of: boldString)
  attributedString.addAttributes(boldFontAttribute, range: range)
  return attributedString
}

Pass the total string and the search string in cellForRowAtIndexPath method and assign return attributedString to you label

It may helps you. Thank you.

Sanjukta
  • 1,057
  • 6
  • 16