extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
By using the above extension you can set text color for label like below
let highest = "160" //Red color
let lowest = "80" //Green color
let stringValue = "$\(highest)/$\(lowest)"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: highest)
attributedString.setColor(color: UIColor.green, forText: lowest)
self.testLabel.attributedText = attributedString
Output Will be like below
