Re: Centering a view in an NSScrollView
Re: Centering a view in an NSScrollView
- Subject: Re: Centering a view in an NSScrollView
- From: Christopher B Hamlin <email@hidden>
- Date: Sun, 20 Jan 2002 16:01:12 -0500
On Saturday, January 19, 2002, at 10:32 PM, Dustin Mierau wrote:
I have a view in an NSScrollView, when the contentSize of the
scrollview is larger than my view I want my view to appear centered
within the scrollview, even as the scrollview is being resized. Right
now it is tagged to the bottom left. I know I can return YES from the
isFlipped method to tag it to the top left, but like I said, I want it
centered. There does not seem to be a good way to do this, any ideas?
OK, try this:
You need to get to the contentView. I think this is the superview of
your view, but I just made an outlet to the NSScrollview called
theScrollView. I had an ivar called savedBounds that was
initialized in awakeFromNib as
savedBounds = [[theScrollView contentView] bounds];
Then, in your drawRect (or wherever you actually
draw), before you draw, check the change in width and
height of the bounds vs your saved version and subtract
half of each difference from the current origin.
The way I think of it is to center the new (larger)
contentView on the old (smaller one).
Given the above settings of theScrollView and savedBounds,
the following basically works for me (not extensively tested, and I'm a
beginner so who knows the side effects?). If you find any problems
I'd like to know about them since I like this and may keep it
in my application now. Thanks! 8)
float dx, dy;
NSRect myBounds;
// find current bounds
myBounds = [[theScrollView contentView] bounds];
if (1) NSLog (@"In redrawView: saved bounds is (%f,%f), %f wide, %f
high)\n",
savedBounds.origin.x, savedBounds.origin.y,
savedBounds.size.width, savedBounds.size.height);
if (1) NSLog (@"In redrawView: content bounds is (%f,%f), %f wide,
%f high)\n",
myBounds.origin.x, myBounds.origin.y,
myBounds.size.width, myBounds.size.height);
// find change from last values
dx = myBounds.size.width - savedBounds.size.width;
dy = myBounds.size.height - savedBounds.size.height;
if (1) NSLog (@"In redrawView: bounds change is (%f,%f)\n", dx, dy);
// move origin to account for size change (probably
// should only be done for non-zero).
[[theScrollView contentView]
setBoundsOrigin:NSMakePoint(myBounds.origin.x - (0.5 * dx),
myBounds.origin.y - (0.5 * dy))];
// recheck w/ NSLog
myBounds = [[theScrollView contentView] bounds];
if (1) NSLog (@"In redrawView: content bounds NOW (%f,%f), %f wide,
%f high)\n",
myBounds.origin.x, myBounds.origin.y,
myBounds.size.width, myBounds.size.height);
// save new version for next check
savedBounds = [[theScrollView contentView] bounds];
Regards,
Chris Hamlin