问题
I am using NSMutableAttributedString to show attributed string in label. Is there way to trim first character of NSMutableAttributedString without change in attributes.
回答1:
No because one of the attributes of the attributes is the range of the string they effect, and those will become invalid if the string length changes.
The best approach would be to reconstruct the attributed string from scratch, which might be simple or difficult, depending on whether you know the attributes to add.
回答2:
NSMutableAttributedString
supports the deleteCharacters(in:NSRange)
method:
@IBOutlet weak var topLabel: NSTextField!
@IBOutlet weak var bottomLabel: NSTextField!
...
let textAttributes : [String : Any] = [
NSForegroundColorAttributeName : NSColor.blue,
NSFontAttributeName : NSFont(name: "Menlo", size: 12.0)!
]
let text = NSMutableAttributedString(string: "ABCDEF",
attributes: textAttributes)
topLabel.attributedStringValue = text
text.deleteCharacters(in: NSMakeRange(0,1))
bottomLabel.attributedStringValue = text
...
来源:https://stackoverflow.com/questions/26383009/trim-first-character-in-nsmutableattributedstring