Search code examples
cocoaautolayout

Autolayout NSCollectionView with subviews


I have an NSCollectionView in one .xib and the subview collection view item for that collection view in another .xib

I am trying to add constraints to my collection view item in order to let it to

  1. Align the edges with the superview's view
  2. Resize itself according to the superview

The collection view item in this second .xib is a NSTableView with constraints as shown in the attachment.

Constraints configuration

Upon startup I get the following

  1. The superview, i.e NSCollectionView is larger than its subviews.
  2. If I resize the entire window and make it smaller, the NSCollectionView will resize itself too, but the subviews do not. See second attachment.

enter image description here


Solution

  • NSCollectionView won't do what you want. The items provide their size to the collection view, which then lays them out in a grid.

    Given the fairly simple, single-row layout you're trying to achieve, you may be able to use an NSStackView. If you don't want to require 10.9 or later, you could make the moral equivalent of a stack view by just creating a plain NSView as your container and then fill it with subviews. You would put this view into a scroll view. The container view would have constraints to keep its top and bottom equal to the clip view's. Its width would not be related to the clip view's. (I don't know if you want the container view's leading edge tied to the clip view's. That might require some experimentation.)

    Set the layout constraints to keep the subviews arranged how you like within the container view and to keep it wide enough to contain them all. You'll want constraints to keep the tops of the subviews related to the top of the container view and similarly for the bottoms. However, make sure the subviews are flexible in their height at least relative to the priority of the view-to-clip-view constraints.