Search code examples
cocoaappkit

How do I append text to the begging of a NSTextView instance?


In my macOS app, there's a NSTextView showing some logs. When a log is generated, I use NSTextView.textStorage.append(NSAttributedString) to add it to the end of the view with a new line character.

(1) I'm not sure know how to add a log to the beginning of the view.

(2) I feel each log should be a seperate element instead of a string with a new line character, should I use other ways to build this log view ?

class LogView: NSTextView {

    func log(text: String) {
        DispatchQueue.main.async {
            self.textStorage?.append(NSAttributedString(string: "\(text)\n", attributes: [NSAttributedStringKey.foregroundColor: NSColor.white]))
        }
    }
}

Solution

  • textStorage inherits from NSAttributedString and if there is append there is also insert(at:)

    class LogView: NSTextView {
    
        func log(text: String) {
            DispatchQueue.main.async {
                self.textStorage?.insert(NSAttributedString(string: "\(text)\n", attributes: [NSAttributedStringKey.foregroundColor: NSColor.white]), at: 0)
            }
        }
    }