Displaying text in a NSScrollView (Swift)

ixany picture ixany · Aug 7, 2014 · Viewed 18.4k times · Source

Just started to learn Swift and created a little macOS app in which I want to use a NSScrollView to display an attributed String. I’ve tried:

@IBOutlet var ScrollViewOutlet : NSScrollView
var attributedString = NSMutableAttributedString(string: myText)
ScrollViewOutlet.insertText(attributedString)

But that doesn’t seem to work. Feels confusing since doing the exact same with a NSTextView instead works like a charm.

What am I missing here?

Answer

Jacksonsox picture Jacksonsox · Nov 18, 2017

In the following example, I added the scrollView in the interface builder as my starting point.

The following works if you your scrollView/textView is empty/blank OR if you need to append text in front of what is already in the scrollView/textView. If there is already text in the box, the new text is inserted in front of the existing text.

The documentView is an NSTextView

Swift 4.0

@IBOutlet weak var imageDestinationDirectory: NSScrollView!

...

let destinationText = "Text to display"
imageDestinationDirectory.documentView!.insertText(destinationText)