我使用此代码将属性字符串添加到标签中:
let attrString = NSMutableAttributedString(string: text)
// add some attributes
myLabel.attributedText = attrString
现在是否可以仅更改属性字符串 myLabel 的文本并保留属性?
通过它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")
注意:只有第一个属性将应用于更新的文本。
更改属性字符串的可变字符串,并将 NSMutableAttributedString 重新分配给标签。
attrString.mutableString.setString("newText")
myLabel.attributedText = attrString
附言如果您无权访问属性字符串变量,请从标签中获取它。
let myAttrString = myLabel.attributedText as? NSMutableAttributedString
if let attrString = myAttrString {
attrString.mutableString.setString("newText")
myLabel.attributedText = attrString
}
获取标签属性
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