Growing NSTextView to fit contents is clipping last line of text

本小妞迷上赌 提交于 2019-12-06 03:49:00

问题


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:

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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17372414/growing-nstextview-to-fit-contents-is-clipping-last-line-of-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!