更改UILabel属性String

J.D*_*Doe 5 nsattributedstring ios swift

我使用此代码将属性字符串添加到标签:

let attrString = NSMutableAttributedString(string: text)
// add some attributes
myLabel.attributedText = attrString
Run Code Online (Sandbox Code Playgroud)

现在是否可以仅更改属性字符串myLabel的文本并保留属性?

sta*_*Man 4

通过它的mutableString财产

例子:

let astrMessage = NSMutableAttributedString(string: "Hello World")

//set some attributes
astrMessage.addAttribute(NSAttributedStringKey.foregroundColor,
                         value: UIColor.blue,
                         range: NSRange(location: 0, length: 5))
astrMessage.addAttribute(NSAttributedStringKey.foregroundColor,
                         value: UIColor.red,
                         range: NSRange(location: 6, length: 5))

//update
astrMessage.mutableString.setString("World Welcome")
Run Code Online (Sandbox Code Playgroud)

注意:只有第一个属性将应用于更新的文本。