matthewjselby
matthewjselby

Reputation: 112

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

Upvotes: 2

Views: 2715

Answers (3)

peterflynn
peterflynn

Reputation: 4906

If you're willing to require 10.11+, you can just select "Detaches Hidden Views" on the NSStackView in Interface Builder (or set detachesHiddenViews = YES on it programmatically).

Then setting View #1 to hidden = YES will automatically re-layout the stack view, making View #2 take up more space (assuming the stack view height is fixed – if not, the stack view would just get less tall instead).


If you need to support 10.10 or earlier, then you can hide the view this way:

[stackView setVisibilityPriority:NSStackViewVisibilityPriorityNotVisible forView:view1];

And show it again via:

[stackView setVisibilityPriority:NSStackViewVisibilityPriorityMustHold forView:view1];

Upvotes: 1

Ken
Ken

Reputation: 13003

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];

Upvotes: 2

Related Questions