like this question, i have an NSView which is the contentView for an NSWindow and it contains several subviews stacked vertically one above the other. some of them are fixed size and some of them can be expanded or collapsed with a disclosure button.
i want to implement a kind of “accordion” effect where expanding or collapsing one of the subviews makes everything else adjust and resizes the superview and the window accordingly.
it really seems like one ought to be able to accomplish this by setting up the right set of constraints with auto layout and i have it now doing the initial layout fine. but i can’t figure out how to set up constraints so that the superview automatically re-sizes to hug the sub-views.
the OP in the question linked above never got an answer and provided his own solution like the one that i was starting to implement independently, but i thought i would throw it out there once again in case there are any auto layout gurus that know a trick. it seems like there should be a way to get the superview to hug the subviews by leveraging auto layout without having to manually calculate the sizes of the subviews and manually reset the size of the superview.
anyone know how?
Autolayout is cool and comprehensive. And arcane.
I tried hard but could not come up with a set of constraints that would do what I wanted to do. It still seems to me that if you stack some NSView’s vertically inside a superview and set up the constraints such that the top subview is pinned to the top of the superview and going down the stack of subviews you pin each one’s top to the bottom edge of the one above and then finally you pin the bottom edge of the last subview to the bottom edge of the superview and you then programmatically resize one or more of the subviews it should be able to pull up or push down on the bottom of the superview to keep it hugging its subviews.
Everything works as expected except for the last piece. When you try to pin the bottom subview to the bottom of the superview, auto layout can’t satisfy all the constraints. It seems like resizing the superview to satisfy the constraints is not in the algorithm. Either that or I am missing some other constraint that needs setting.
And while I am on the subject, looking at the debugger, it appears that there are un-settable constrains at play between a window’s contentView and the window frame. I kind of wonder if being able to mess with those constraints would let the original scheme work.
Anyway, I did come up with a solution that uses autolayout and it is pretty close to what I was hoping autolayout would do because all that was necessary was subclassing NSView and putting a few lines of code into the intrinsicSize method and then using that subclass for the superview.
i created an xcode project that has my collapsible views base classes and a working demo of the whole thing on github.