Search code examples
cocoaappkitnsscrollview

Expanding documentView in NSScrollView


I have an NSSplitView that contains 2 side-by-side panes, and in the right-hand pane, there is an NSScrollView. I have a separate XIB file that contains the view (inspectorView) that I want to embed in the scroll view, which I do like so:

self.scrollView.documentView = inspectorView

This works perfectly, however, when I make the split view pane a bit wider my inspectorView doesn't grow horizontally to fill the space. Using -NSShowAllviews YES I've confirmed that the scroll view is correctly resizing, however, the inspectorView remains the same width as it was when it was originally assigned to scrollView.documentView. Herein lies my problem... I want it to expand to fill the split view width.

I'm using autolayout for everything and all of my views are created using XIBs. The only thing I'm doing programatically is setting the documentView property of the scroll view.

If I was adding the inspectorView as a subview, then it is easy to add constraints that tell it to grow to fill the parent view. However, I'm not sure what the equivalent mechanism is when setting the documentView of an NSScrollView. Any suggestions? Thanks.

Edit

As is often the way, 20 minutes after I posted this, I discovered one way to get it to work, which is to set the auto resizing mask and then get it to translate that mask into constraints.

inspectorView.autoresizingMask = .ViewWidthSizable
inspectorView.translatesAutoresizingMaskIntoConstraints = true
self.scrollView.documentView = inspectorView

Normally, I'm setting translatesAutoresizingMaskIntoConstraints to false, not true. Anyway, as I said, this seems to work however I'm not yet convinced this is the right way. Thoughts?


Solution

  • You can simply pin the document-view's left and right edges to the corresponding edges of its superview - the scroll view's contentView (an NSClipView instance):

    // docView and scrollView defined elsewhere.
    // In both cases translatesAutoresizingMaskInConstraints is set to false.
    
    scrollView.documentView = docView
    
    let viewsDict = ["docView" : docView]
    scrollView.contentView.addConstraints(
        NSLayoutConstraint.constraintsWithVisualFormat("H:|[docView]|", 
            options: .allZeros, 
            metrics: nil, 
            views: viewsDict) 
    )
    

    That should work in your case, where it sounds like you've already got the vertical size of the document view behaving as you require.