简体   繁体   中英

Is it possible to highlight a substring of text inside of a tableView cell?

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 " A pple" and "Or a nge"

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:

我正在努力实现这样的目标

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM