更改 UILabel 属性字符串

Change UILabel attributed String

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

let attrString = NSMutableAttributedString(string: text)
// add some attributes
myLabel.attributedText = attrString

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

获取标签属性

let linkAttributes = NSMutableAttributedString(attributedString: label.attributedText)

你可以给添加属性。

linkAttributes.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: linkRange)
let linkAttributes: [String : Any] = [
    NSForegroundColorAttributeName: UIColor.green,
    NSUnderlineColorAttributeName: UIColor.lightGray,
    NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]

将属性文本添加到您的标签

myLabel.attributedText = linkAttributes 

更改属性字符串的可变字符串并将 NSMutableAttributedString 重新分配给您的标签。

attrString.mutableString.setString("newText")
myLabel.attributedText = attrString

P.S 如果您无权访问您的属性字符串变量,请从标签中获取它。

let myAttrString = myLabel.attributedText as? NSMutableAttributedString
if let attrString = myAttrString {
    attrString.mutableString.setString("newText")
    myLabel.attributedText = attrString
}

通过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")

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