Skip to content

Instantly share code, notes, and snippets.

@PauloLeon
Created August 12, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PauloLeon/8609daab8518d9bca1991638e840b5f7 to your computer and use it in GitHub Desktop.
Save PauloLeon/8609daab8518d9bca1991638e840b5f7 to your computer and use it in GitHub Desktop.
extension String {
func withHighlightedText(highlightedPartsOfString: Array<NSString>, font: UIFont, newFont: UIFont) -> NSAttributedString {
let nonHighlightedFontAttribute = [NSAttributedString.Key.font:font]
let highlightedFontAttribute = [NSAttributedString.Key.font:newFont]
let newText = NSMutableAttributedString(string: self as String, attributes: nonHighlightedFontAttribute)
for i in 0 ..< highlightedPartsOfString.count {
newText.addAttributes(highlightedFontAttribute, range: (self as NSString).range(of: highlightedPartsOfString[i] as String))
}
return newText
}
}
//Usage
let boldLabel = UILabel()
let font = UIFont(name: "AvenirNext-Italic", size: 24)!
let boldFont = UIFont(name: "AvenirNext-BoldItalic", size: 24)
boldLabel.attributedText = "testando esse código em negrito".withHighlightedText(
highlightedPartsOfString: ["código", "negrito"], font: font, newFont: boldFont)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment