-1

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.

1 Answers1

1

I can't see what is different here and why it doesn't work.

The issue is merely that you've made this odd decision to cycle through the string by word. Well, forward slash is a word divider, so the words are

R09
27
R13
51
R22
08
R11
11

None of those is a match for any of your redText or orangeText strings. No match, no color.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I guess it makes sense why it works on the other app which doesn’t have a slash. What can I cycle with to include the divider or cycle with space? –  Jun 05 '20 at 06:41