如何在 Cocoa 中自动滚动 NSTextView 以在窗口上垂直居中文本?

发布于 2024-10-21 18:05:46 字数 670 浏览 3 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请恋爱 2024-10-28 18:05:46

好吧,我找到了一个解决方案:

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是距应设置插入点的底部的距离(以像素为单位)。只需尝试一下即可了解它是如何工作的。

Well, I found a solution:

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];

where textView is the IBOutlet to the textview and scrolling 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文