6

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?

ppilone
  • 1,082
  • 1
  • 10
  • 16

2 Answers2

0

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.

Seb Jachec
  • 3,003
  • 2
  • 30
  • 56
  • Thanks - I'm using auto layout (and relying on it) in the text view's parent view so I'm not sure I'll be able to use your expanding text view. Hoping it will point me in the right direction though. – ppilone Jul 01 '13 at 02:30
  • how did you get your code to work? I'm using it in a chat like interface (your textview for the bottom) and its' not working. Same issue as above. – KVISH Mar 31 '16 at 03:50
  • I just revisited my code (after 3 years..) and I think I've got it working with AutoLayout. I'll commit my changes to GitHub in a second – Seb Jachec Mar 31 '16 at 09:18
0

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.

harrisg
  • 613
  • 7
  • 12