Skip to content

Instantly share code, notes, and snippets.

@vinczebalazs
Last active June 29, 2020 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vinczebalazs/54dffe5e0e8f4f7d63dcbe5c9590bcaf to your computer and use it in GitHub Desktop.
Save vinczebalazs/54dffe5e0e8f4f7d63dcbe5c9590bcaf to your computer and use it in GitHub Desktop.
NSAttributedString+Highlight
extension NSAttributedString {
func highlighting(_ substring: String, using color: UIColor) -> NSAttributedString {
let attributedString = NSMutableAttributedString(attributedString: self)
attributedString.addAttribute(.foregroundColor, value: color, range: (self.string as NSString).range(of: substring))
return attributedString
}
}
// Usage:
label.attributedText = NSAttributedString(string: "Budapest")
label.attributedText = label.attributedText?.highlighting("Bud", using: .blue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment