I'm trying to colour occurrences of a string in a string using the below:
let text = "R09/27 R13/51 R22/08 R11/11"
let attributed = text.color2(redText: ["R09/27", "R11/11"], orangeText: ["R13/51"])
print(attributed)
textLabel.attributedText = attributed
And with the following extension:
extension String {
func color2(
redText: [String],
orangeText: [String]
) -> NSAttributedString {
let result = NSMutableAttributedString(string: self)
enumerateSubstrings(in: startIndex..<endIndex, options: .byWords) {
(substring, substringRange, _, _) in
guard let substring = substring else { return }
if redText.contains(substring) {
result.addAttribute(
.foregroundColor,
value: UIColor.systemRed,
range: NSRange(substringRange, in: self)
)
}
if orangeText.contains(substring) {
result.addAttribute(
.foregroundColor,
value: UIColor.systemOrange,
range: NSRange(substringRange, in: self)
)
}
}
return result
}
}
However the string will not color. When I print the attribute in the console it doesn't show any attributes like normally but rather { }. Does anyone know why my text won't color the occurrences? I have used this code before in another app and worked fine, I can't see what is different here and why it doesn't work.