Padding around an NSTextView in an NSScrollView

2019-03-22 07:57发布

问题:

I'd like to provide a few pixels of padding around an NSTextView inside of an NSScrollView. I've reviewed this post and using setTextContainerInset does the trick for the left, right, and bottom margins. But as soon as the text scrolls the top buffer is lost. Same thing with overriding textContainerOrigin. Another answer in that post states:

The way TextEdit does it (when in Wrap to Page mode) is to put the text view inside of a larger view, and set that larger view as the document view of the scroll view.

But if I do that (using, say an NSBox) the content no longer scrolls. Am I missing something regarding that particular trick, or are there any other techniques that folks could suggest?

回答1:

There's a step that seems to be missing from your quote. You'll need to make sure your new document view tracks the changes in the text view's frame and sizes itself to fit. You can turn on NSViewFrameDidChangeNotification on your text view with -setPostsFrameChangedNotifications:, then have your new document view listen for notifications from your text view..



回答2:

By the way, I ended up accomplishing this by subclassing NSClipView, overriding setFrame:, setFrameOrigin:, and setFrameSize, and hacking the origin and width in those methods to add my padding.