【问题标题】:How to autoscroll NSTextView in Cocoa to center text vertically on the window?如何在 Cocoa 中自动滚动 NSTextView 以在窗口上垂直居中文本?
【发布时间】:2011-03-12 11:36:39
【问题描述】:

我正在创建一个在 NSScrollView 内带有 NSTextView 的文本编辑器,并且希望在用户插入一些文本时自动滚动 textview,以便插入的文本垂直居中在窗口(或 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];
}

【问题讨论】:

    标签: cocoa scroll nstextview nsscrollview


    【解决方案1】:

    嗯,我找到了解决办法:

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

    【讨论】:

    • 您好,您在哪里使用此代码?子类 nstextview 和 textdidchange?我想要这样的'而打字活动行(带插入点)应始终保持在屏幕中间,活动文本行(带光标)应与文本的其余部分具有不同的颜色'
    • 是的,我将shouldChangeTextInRange 设置为实例变量的insertionRectdidChangeText 使用最后两行的子类。希望这会有所帮助。
    • 谢谢,但它不起作用:/ 我有 -(BOOL)shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString{ insertRect =[[self layoutManager] boundingRectForGlyphRange:[self selectedRange] inTextContainer :[self textContainer]];返回是; } -(void)didChangeText{ CGFloat 滚动=[[NSScreen mainScreen] frame].size.height/2; NSPoint scrollPoint=NSMakePoint(0,insertionRect.origin.y+insertionRect.size.height+2*scrolling-[[NSScreen mainScreen] frame].size.height); [自滚动点:滚动点]; }
    猜你喜欢
    • 2012-05-08
    • 2018-02-02
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多