vincentf
vincentf

Reputation: 1499

How to change text color of NSTextView

How can I change the color of all text in a NSTextView? In the example below, myTextView.textColor = .white only changes color of Hello but not World. I don't want to specify the color every time when I append some text.

Also I'm not sure if this is an appropriate way appending text to NSTextView.

    override func viewDidLoad() {
        super.viewDidLoad()

        myTextView.string = "Hello"
        myTextView.backgroundColor = .black
        myTextView.textColor = .white

        logTextView.textStorage?.append(NSAttributedString(string: "World"))
    }

Upvotes: 2

Views: 1044

Answers (1)

Code Different
Code Different

Reputation: 93191

NSTextStorage is a subclass of NSMutableAttributedString so you can manipulate it as a mutable attributed string.

If you want the new text to carry on the attributes at the end of the current text, append to the mutable string:

myTextView.textStorage?.mutableString.append("World")

If you want to add more attributes to the new text (for example, adding an underline), get the attributes at the end of the current text and manipulate the attributes dictionary:

guard let textStorage = myTextView.textStorage else {
    return
}
var attributes = textStorage.attributes(at: textStorage.length - 1, effectiveRange: nil)
attributes[.underlineStyle] = NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)

textStorage.append(NSAttributedString(string: "World", attributes: attributes))

After this, if you call mutableString.append, the new text will be in white and underlined.

Upvotes: 1

Related Questions