views:

438

answers:

1

How do I center an NSView within an NSScrollView like the way "Preview" does?

+4  A: 

Read the Scroll View Programming Guide section on scrolling to a specific position. There are examples there for top or bottom. You'd just change the math to calculate the origin based on middle of your NSView. Something like:

-(void)scrollToCenter:(NSScrollView*)scrollView
{
    const CGFloat midX = NSMidX([[scrollView documentView] bounds]);
    const CGFloat midY = NSMidY([[scrollView documentView] bounds]);

    const CGFloat halfWidth = NSWidth([[scrollView contentView] frame]) / 2.0;
    const CGFloat halfHeight = NSHeight([[scrollView contentView] frame]) / 2.0;

    NSPoint newOrigin;
    if([[scrollView documentView] isFlipped])
    {
        newOrigin = NSMakePoint(midX - halfWidth, midY + halfHeight);
    }
    else
    {
        newOrigin = NSMakePoint(midX - halfWidth, midY - halfHeight);
    }

    [[scrollView documentView] scrollPoint:newOrigin];
}
nall