1
votes

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
You have to put the text view in a scroll view to make the text view scrollable. I have not done this in code so I cannot provide an example. It is easier to add a text view to your view controller in Interface Builder because the text view object includes a scroll view for you. - Swift Dev Journal

1 Answers

9
votes

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
}