Search code examples
macosautolayoutinterface-buildernsscrollview

Why are the contents of an NSScrollView aligned to the bottom instead of the top?


I'm trying to use an NSScrollView where the contents may be (vertically) smaller or taller than the window, changing dynamically at runtime. (This will later be a stack view with multiple views that can be shown/hidden at random.) When the contents are larger than the scroll view, everything works as expected; but when the contents are vertically smaller than the scroll view, they are displayed at the bottom of the scroll view instead of the top, where I would like them. This is despite the fact that I have added a constraint anchoring the top of the content (for testing: just a fixed-height NSBox embedded in an NSScrollView) to the top of its superview.

Some testing shows that the clip view's height follows the scroll view's height, and its origin stay the same; so I would assume that when I constrain the NSBox' top to the top of its superview (which is the clip view), it would show at the top, but instead it is displayed at the bottom.

This behavior is different from when I embed the NSBox in a simple NSView; when I do this, with the same constraints, the box is shown at the top.

Why is this happening, and how can I solve this?


Solution

  • After some experimenting I was able to solve this problem.

    One half of the answer is in Setting NSScrollView Contents to Top Left Instead of Bottom Left When Document Swapping : Inserting a custom view that returns YES to -isFlipped in the hierarchy between the clip view and the content.

    I was able to solve the remaining part of the problem by changing the constraints: I had to constrain the edges of the custom view not to the container (the clip view of the NSScrollView), but rather to the inner view (in my test case, the NSBox). Two additional constraints connect the top and left edges of the custom "flip" view to the clip view.