Centering a documentView inside an NSScrollView

This took me a while to sort out, but I finally figured it out.

Basically if you want to have the documentView of a NSScrollView be centered in the view if the content area of the NSScrollView is bigger than the size of the document view, you would override the NSClipView class with a custom class. This class would then implement the -constrainBoundsRect: method as follows:

@implementation GClipView

- (NSRect)constrainBoundsRect:(NSRect)proposed
{
	NSRect r = [super constrainBoundsRect:proposed];
	NSRect doc = [self.documentView frame];

	if (proposed.size.width > doc.size.width) {
		r.origin.x = floor((doc.size.width - proposed.size.width)/2);
	}
	if (proposed.size.height > doc.size.height) {
		r.origin.y = floor((doc.size.height - proposed.size.height)/2);
	}

	return r;
}

@end

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s