6
votes

I'm trying to create an NSTextView that grows vertically as the user types and scrolls once the height has reached a maximum. This is similar to the text view in Messages works.

My first attempt uses the delegate to listen for text changes and adjust the height constraint associated with the NSTextView's scroll view:

- (void)textDidChange:(NSNotification *)notification
{
    NSTextView *textView = self.textView;
    NSRect usedRect = [textView.textContainer.layoutManager usedRectForTextContainer:textView.textContainer];
    NSLog(@"DEBUG: used rect: %@", NSStringFromRect(usedRect));
    self.textViewHeightConstraint.constant = MIN(80.f, MAX(usedRect.size.height, 30.f));
}

This almost works: the text view's (scroll view's) height is updated as I type, however, the last line of text is clipped:

enter image description here

Once the scroll view reaches it's max height and begins scrolling it works nicely. I've tried forcing a display/layout/constraint update on the enclosing scroll view with no luck. My guess is the clip view of the scroll view isn't updating correctly, and it's clipping the bottom of the text view. Is there any way to force the clip view/scroll view to update appropriately when the constraint changes?

2

2 Answers

0
votes

I'm not sure if it would be any use, but I wrote a vertically-expanding NSTextView subclass, which is available on GitHub. Feel free to take a look or adjust as you want.

0
votes

I believe that you are setting the NSTextView's height to the size needed for the textContainer but you aren't accounting for the inset that the text view is adding. Try adding the height of -[NSTextView textContainerInset] to your calculated height.

The documentation doesn't really specify, but I'm assuming that textContainerInset returns the total inset for width/height on all sides and that -[NSTextView textContainerOrigin] would roughly split that in half.