Skip to content

Instantly share code, notes, and snippets.

@DevinThompson
Last active December 18, 2019 00:00
Show Gist options
  • Save DevinThompson/d89db41fb032dc6389b1ae589e324197 to your computer and use it in GitHub Desktop.
Save DevinThompson/d89db41fb032dc6389b1ae589e324197 to your computer and use it in GitHub Desktop.
Change the color of a single word in an attributed text string
// Change the color of one word
upperTextView.headerLabel.textColor = .textGray
if let text = upperTextView.headerLabel.text {
if let range = text.range(of: "style")?.nsRange(in: text) {
(text as NSString).substring(with: range)
if let myString = upperTextView.headerLabel.attributedText {
let mutable = NSMutableAttributedString(attributedString: myString)
mutable.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range: range)
upperTextView.headerLabel.attributedText = mutable
}
}
}
// for converting range to NSRange
extension RangeExpression where Bound == String.Index {
func nsRange<S: StringProtocol>(in string: S) -> NSRange { .init(self, in: string) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment