更改字符串数组中特定文本的颜色。 Swift

Change the color of specific texts within an array of string. Swift

如何更改将要传递到标签中的字符串数组中特定文本的颜色?

假设我有一个字符串数组:

var stringData = ["First one", "Please change the color", "don't change me"]

然后传递给一些标签:

Label1.text = stringData[0]
Label2.text = stringData[1]
Label3.text = stringData[2]

更改 stringData[1] 中单词 "the" 颜色的最佳方法是什么?

预先感谢您的帮助!

let str = NSMutableAttributedString(string: "Please change the color")
str.addAttributes([NSForegroundColorAttributeName: UIColor.red], range: NSMakeRange(14, 3))
label.attributedText = str

range是特定文本的范围。

如果您想更改字符串中所有 the 的颜色:

func highlight(word: String, in str: String, with color: UIColor) -> NSAttributedString {
    let attributedString = NSMutableAttributedString(string: str)
    let highlightAttributes = [NSForegroundColorAttributeName: color]

    let nsstr = str as NSString
    var searchRange = NSMakeRange(0, nsstr.length)

    while true {
        let foundRange = nsstr.range(of: word, options: [], range: searchRange)
        if foundRange.location == NSNotFound {
            break
        }

        attributedString.setAttributes(highlightAttributes, range: foundRange)

        let newLocation = foundRange.location + foundRange.length
        let newLength = nsstr.length - newLocation
        searchRange = NSMakeRange(newLocation, newLength)
    }

    return attributedString
}

label2.attributedText = highlight(word: "the", in: stringData[1], with: .red)