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

时间:2016-12-08 03:25:48

标签: swift colors textcolor nsmutableattributedstring

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

我们说我有一个字符串数组:

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]?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

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

range是特定文字的范围。

答案 1 :(得分:1)

如果您想更改字符串中所有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)