开发者

How to autoscroll NSTextView in Cocoa to center text vertically on the window?

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开发者_如何学Go 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];
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜