我想创建一个NSTextView,在用户输入时垂直增长并在高度达到最大值后滚动。这类似于"消息"中的文本视图。
我的第一次尝试是使用委托来监听文本更改,并调整与NSTextView滚动视图关联的高度约束:
- (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));
}
这个方法基本可行:文本视图(滚动视图)的高度随着输入而更新,然而,文本的最后一行被裁剪了:
![enter image description here](https://istack.dev59.com/2fMIA.webp)