Search code examples
macoscocoaautolayoutnsstackview

Using Cocoa autolayout to hide and show a view


I'm trying to hide and show view #1 in the following picture based on whether the button is clicked using Autolayout. Anyone know how to do this?

I tried setting two NSLayoutConstraints for view #2, one where it is tied to the top of the superview of view #1 and view #2 and one where it is tied to the bottom of view #1, and then alter the priority of the NSLayoutConstraints to hide view #1, but that didn't seem to do anything.

Any advice would be appreciated. I'm mainly trying to do this in IB, but programatic solutions are welcome as well.

Pic for reference:

View test


Solution

  • NSStackView is appropriate here. It automates creating constraints that tie its subviews to each other in stack.

    Hiding a view does not change layout. It's still there, just isn't drawing.

    If you were doing it without NSStackView, what you would do is change the constraints. Keep an instance variable, _stackConstraints. In one configuration, the stack constraints would be

    V:|-[0]-[view1(v1Height)]-0-[view2]-0-[view3(v3Height)]-0-|
    

    and in the other configuration

    V:|-[0]-[view2]-0-[view3(v3Height)]-0-| 
    

    When you hit the button, do

    [[self view] removeConstraints:_stackConstraints];
    _stackConstraints = <make other set of constraints>
    [[self view] addConstraints:_stackConstraints];