如何在 Cocoa 中自动滚动 NSTextView 以在窗口上垂直居中文本?
我正在 NSScrollView 内创建一个带有 NSTextView 的文本编辑器,并且希望每当用户插入一些文本时自动滚动文本视图,以便插入的文本在窗口(或文本视图)上垂直居中。我发现这个示例代码可以滚动到滚动视图的顶部,但无法真正理解它是如何工作的。我已经搞乱了这段代码,但我的文本视图似乎只是上下跳跃,没有任何逻辑。谁能帮助我吗?
- (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];
}
I'm creating a text editor with a NSTextView inside a NSScrollView and would like to automatically scroll the textview whenever the user inserts some text, so that the inserted text is vertically centered on the window (or on the textview). I found this sample code to scroll to the top of a scrollview, but can't really understand how it works. I've already messed around with this code, but my textview just seems to jump up and down without any logics. Can anyone help me?
- (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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我找到了一个解决方案:
其中textView是textview的
IBOutlet
,而scrolling
是距应设置插入点的底部的距离(以像素为单位)。只需尝试一下即可了解它是如何工作的。Well, I found a solution:
where textView is the
IBOutlet
to the textview andscrolling
is the distance in pixels from the bottom where the insertion point should be set. Just play around with it to understand how it works.