DEV Community

Khoa Pham
Khoa Pham

Posted on

2 1

How to make scrollable NSTextView in AppKit

When adding NSTextView in xib, we see it is embedded under NSClipView. But if we try to use NSClipView to replicate what's in the xib, it does not scroll.

To make it work, we can follow Putting an NSTextView Object in an NSScrollView and How to make scrollable vertical NSStackView to make our ScrollableInput

For easy Auto Layout, we use Anchors for UIScrollView.

Things worth mentioned for vertical scrolling

textContainer.heightTracksTextView = false
textView.autoresizingMask = [.width]
textView.isVerticallyResizable = true
class ScrollableInput: NSView {
    let scrollView = NSScrollView()
    let textView = NSTextView()

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)

        let rect = CGRect(
            x: 0, y: 0,
            width: 0, height: CGFloat.greatestFiniteMagnitude
        )

    let layoutManager = NSLayoutManager()

        let textContainer = NSTextContainer(size: rect.size)
        layoutManager.addTextContainer(textContainer)
        textView = NSTextView(frame: rect, textContainer: textContainer)
        textView.maxSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)

        textContainer.heightTracksTextView = false
        textContainer.widthTracksTextView = true

        textView.isRichText = false
        textView.importsGraphics = false
        textView.isEditable = true
        textView.isSelectable = true
        textView.font = R.font.text
        textView.textColor = R.color.text
        textView.isVerticallyResizable = true
        textView.isHorizontallyResizable = false

        addSubview(scrollView)
        scrollView.hasVerticalScroller = true
        scrollView.drawsBackground = false
        scrollView.drawsBackground = false
        textView.drawsBackground = false

        activate(
            scrollView.anchor.edges
        )

        scrollView.documentView = textView
        textView.autoresizingMask = [.width]
    }

    required init?(coder decoder: NSCoder) {
        fatalError()
    }
}

Original post https://github.com/onmyway133/blog/issues/330

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more