Last active
December 18, 2019 00:00
-
-
Save DevinThompson/d89db41fb032dc6389b1ae589e324197 to your computer and use it in GitHub Desktop.
Change the color of a single word in an attributed text string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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