我正在 NSScrollView 中创建一个带有 NSTextView 的文本编辑器,并且希望每当用户插入一些文本时自动滚动 TextView ,以便插入的文本在窗口(或 TextView )上垂直居中。我发现这个示例代码可以滚动到 ScrollView 的顶部,但无法真正理解它是如何工作的。我已经搞乱了这段代码,但我的 TextView 似乎只是上下跳跃,没有任何逻辑。谁能帮我吗?
- (void)scrollToTop:sender;
{
NSPoint newScrollOrigin;
// assume that the scrollview is an existing variable
if ([[scrollview documentView] isFlipped]) {
newScrollOrigin=NSMakePoint(0.0,0.0);
} else {
newScrollOrigin=NSMakePoint(0.0,NSMaxY([[scrollview documentView] frame])
-NSHeight([[scrollview contentView] bounds]));
}
[[scrollview documentView] scrollPoint:newScrollOrigin];
}
最佳答案
好吧,我找到了解决方案:
NSRect insertionRect=[[self layoutManager] boundingRectForGlyphRange:[self selectedRange] inTextContainer:[self textContainer]];
NSPoint scrollPoint=NSMakePoint(0,insertionRect.origin.y+insertionRect.size.height+2*scrolling-[[NSScreen mainScreen] frame].size.height);
[self scrollPoint:scrollPoint];
其中textView是textview的IBOutlet
,而scrolling
是距应设置插入点的底部的距离(以像素为单位)。只需尝试一下即可了解其工作原理。
关于cocoa - 如何在 Cocoa 中自动滚动 NSTextView 以在窗口上垂直居中文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5282245/