There are lots of examples out there of how to get NSScrollView to center its document view. Here are two examples (which are so similar that somebody is copying somebody without attribution, but the point of how is there.) http://www.bergdesign.com/developer/index_files/88a764e343ce7190c4372d1425b3b6a3-0.html https://github.com/devosoft/avida/blob/master/apps/viewer-macos/src/main/CenteringClipView.h
This is normally done by subclassing NSClipView and overriding:
- (NSPoint)constrainScrollPoint:(NSPoint)newOrigin;
But this method is deprecated in Mac OS X 10.9 +
What can we do now? Oh noes~!
Well, the answer is simple and nowhere near as over bloated as those are. Those do not work with double-tap magnification anyway.
This does. It just works. You can also customize your adjustments as needed.
In the @implementation you only need to implement an override of constrainBoundsRect:
In the @interface just add one single property. This allows you to not use centering. As you can imagine, there may be conditional logic you want to turn centering off at times.
@property BOOL centersDocumentView;
Also, be sure to set this
BOOL
toYES
orNO
in your override ofinitWithFrame
andinitWithCoder:
so you'll have a known default value to work from.
(remember kids,
initWithCoder:
allows you to do the needful and set a view's class in a nib. Don't forget to call super prior to your stuff!)Of course if you need to support anything earlier than 10.9 you'll need to implement the other stuff.
(though probably not nearly as much as others have...)
The answer above by uchuugaka works very well and, as pointed out, it is very much simpler than older solutions.
The code above calls the function
centeredCoordinateUnitWithProposedContentViewBoundsDimensionAndDocumentViewFrameDimension()
, but the source for this isn't provided.The function is trivial, but for completeness here's an an implementation:
Here working class for swift
1) make sure the view (documentView) directly under the clip view has no constraints to the clip view! (if so, check, remove at build time)
2) subclass NSClipView
3) change the NSClipView to your subclass