2

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"))
    }
vincentf
  • 1,419
  • 2
  • 20
  • 36
  • 1
    check adding attribute with `NSForegroundColorAttributeName` for you `NSAttributedString` [sample](https://stackoverflow.com/questions/25207373/changing-specific-texts-color-using-nsmutableattributedstring-in-swift) – Özgür Ersil Jan 26 '18 at 11:25
  • myTextView only has the string "Hello". you are appending attributed text to logTextView. When using Swift it's best to stick to Swift bridged classes. use UITextView instead of NSTextView – Scriptable Jan 26 '18 at 11:25
  • It's a macOS app – vincentf Jan 26 '18 at 11:30

1 Answers1

1

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.

Code Different
  • 90,614
  • 16
  • 144
  • 163