Created
October 24, 2017 10:43
-
-
Save AlexZverusha/2b753fda868d1771c79093737171b76c to your computer and use it in GitHub Desktop.
UILabel with text of two different colors
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
extension NSMutableAttributedString{ | |
func setColorForText(_ textToFind: String, with color: UIColor) { | |
let range = self.mutableString.range(of: textToFind, options: .caseInsensitive) | |
if range.location != NSNotFound { | |
addAttribute(NSForegroundColorAttributeName, value: color, range: range) | |
} | |
} | |
} | |
Usage! | |
func setColoredLabel() { | |
let string = NSMutableAttributedString(string: "Here is a red blue and green text") | |
string.setColorForText("red", with: #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)) | |
string.setColorForText("blue", with: #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)) | |
string.setColorForText("green", with: #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)) | |
mylabel.attributedText = string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment