Arun
Arun

Reputation: 85

Trim first character in NSMutableAttributedString

I am using NSMutableAttributedString to show attributed string in label. Is there way to trim first character of NSMutableAttributedString without change in attributes.

Upvotes: 2

Views: 1521

Answers (2)

wcochran
wcochran

Reputation: 10906

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
...

Upvotes: 2

Droppy
Droppy

Reputation: 9731

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.

Upvotes: 3

Related Questions