Pierre Houston
Pierre Houston

Reputation: 1641

Trouble with autolayout on NSScrollView's document view

I'm trying to find the best way to use Lion's autolayout to make this simple window containing a scrollable view with a centered image and a border around it. See my awesome ascii art:

+==============+
|             ||
|    XXXXXX   ||
|    XXXXXX   ||
|    XXXXXX   ||
|              |
+--------------+

The NSScrollView's document view is a flipped NSView subclass that draws a background pattern, and inside that I add an image that the user chooses (ie. indeterminate size). When adding the image view, I give it constraints to center it in the document view. The document view itself is given constraints saying it wants to be slightly larger than the loaded image. What I'm wanting is the obvious behavior: on loading an image larger than the scollview, the scrollers become active, on resizing the window the scrollers activate / deactivate normally.

However, when loading a large image I'm seeing is the document view expanding all right, but the scroll view & window expand with it! After that point the window doesn't permitting resizing any smaller. Obviously I'm not doing it right, but I can't see why.

I tried changing the priority of the constraints of the document view, anything above NSLayoutPriorityWindowSizeStayPut and the window expands as above (makes sense I guess), but anything lower and the document view never resizes, resizing the window smaller works but the scrollers aren't enabled.

Does anyone know if there are other priorities I need to set elsewhere, or additional constraints I need, or a different approach altogether .. should I instead be setting the document view's "intrinsic size"? Also pointers to any autolayout open source / sample code I haven't seen yet would be cool.

Upvotes: 2

Views: 2015

Answers (1)

Pierre Houston
Pierre Houston

Reputation: 1641

This turned out to be the old translatesAutoresizingMaskIntoConstraints gotcha. When I was having these problems I was setting the NSScrollView's document view within Interface Builder.

I changed to creating the view at runtime (or I could have defined it separately in IB as a "loose" view) and then connecting it in my window controller:

self.backgroundPatternView.translatesAutoresizingMaskIntoConstraints = NO;
self.scrollView.documentView = self.backgroundPatternView;

After this change, the default priorities worked fine.

Upvotes: 2

Related Questions