NSTextView Scrolling

Viewed 2314

How to make a NSTextView scrollable ?

Problem:

  • Text View is displayed but is not scrollable. I have to resize the window to see more contents

Question:

  • How to make the text view scrollable.

Code:

class ViewController: NSViewController {

    private let textView                = NSTextView()

    //MARK: Manage Views

    override func viewDidLoad() {
        super.viewDidLoad()

        setupTextView()
    }


    private func setupTextView() {

        textView.isEditable      = false

        view.addSubview(textView)

        textView.translatesAutoresizingMaskIntoConstraints = false

        textView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        textView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
}
1 Answers

NSTextView doesn't scroll, place the text view inside a NSScrollView. Class method scrollableTextView() of NSTextView returns a NSTextView in a NSScrollView.

private var textView:NSTextView?

private func setupTextView() {

    let scrollView = NSTextView.scrollableTextView()
    textView = scrollView.documentView as? NSTextView

    textView?.isEditable      = false

    view.addSubview(scrollView)

    scrollView.translatesAutoresizingMaskIntoConstraints = false

    scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
Related