Swift 3 :
extension NSMutableAttributedString {
func setColorForText(textToFind: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
if range != nil {
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
}
func setColoredLabel() {
var string: NSMutableAttributedString = NSMutableAttributedString(string: "My label with red blue and green colored text")
string.setColorForText(textToFind: "red", withColor: UIColor.red)
string.setColorForText(textToFind: "blue", withColor: UIColor.blue)
string.setColorForText(textToFind: "green", withColor: UIColor.green)
mylabel.attributedText = string
}
Результат: