根据变量字符串中的出现为字符串着色

Color a string based on occurrences in a Variable String

我正在尝试创建一个函数,该函数允许输入字符串为某些单词着色,然后该函数将 return 着色字符串。

我先从红色开始,但不知道如何让它发挥作用。

到目前为止我的代码:

let oldString = "TEST STRING TO COLOUR IT WORDS EXIST" //sample of a variable string that may or may not contain wors that need coloring

let newString = stringColorCoding(stringToColor: oldString, colorRed: "TO, POT, TEST", colorYellow: "EXIST, TOP", colorGreen: "AB, +TA, -XY, WORDS")

func stringColorCoding(stringToColor: String, colorRed: String, colorYellow: String, colorGreen: String)
{

let attrStr = NSMutableAttributedString(string: stringToColor)
let inputLength = attrStr.string.count
let searchStringRed = colorRed
let searchLengthRed = searchStringRed.characters.count
var rangeRed = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) 
{
  range = (attrStr.string as NSString).range(of: searchStringRed, options: [], range: range)
     if (range.location != NSNotFound) 
   {
     attrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.systemRed, range: NSRange(location: range.location, length: searchLengthRed))
     range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
     }
  }
 return attrStr
}

你的处理方式相当复杂。我会使用 enumerateSubstrings 来获取字符串中的每个单词。然后,我没有传递带有搜索词的逗号分隔字符串,而是传递了一个搜索字符串数组。

extension String {
    func highlighted(
        redText: [String],
        yellowText: [String],
        greenText: [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 yellowText.contains(substring) {
                result.addAttribute(
                    .foregroundColor,
                    value: UIColor.systemYellow,
                    range: NSRange(substringRange, in: self)
                )
            }
            if greenText.contains(substring) {
                result.addAttribute(
                    .foregroundColor,
                    value: UIColor.systemGreen,
                    range: NSRange(substringRange, in: self)
                )
            }
        }
        return result
    }
}

用法如下:

let highlighted = "TEST TO COLOUR IT WORDS EXIST".highlighted(
    redText: ["TO", "POT", "TEST"],
    yellowText: ["EXIST", "TOP"],
    greenText: ["AB", "+TA", "-XY", "WORDS"]
)