简体   繁体   English

使用可可自动布局来隐藏和显示视图

[英]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. 我试图根据是否使用“自动布局”单击按钮,在下图中隐藏并显示视图1。 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. 我尝试为视图2设置两个NSLayoutConstraints,其中一个NSView绑定到视图1和视图2的超级视图的顶部,一个绑定到视图1底部的视图,然后更改视图2的优先级。 NSLayout限制隐藏视图1,但这似乎无济于事。

Any advice would be appreciated. 任何意见,将不胜感激。 I'm mainly trying to do this in IB, but programatic solutions are welcome as well. 我主要是在IB中尝试这样做,但是也欢迎使用编程解决方案。

Pic for reference: 图片供参考:

查看测试

NSStackView is appropriate here. NSStackView适合此处。 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. 如果您在没有NSStackView的情况下进行操作,则要做的就是更改约束。 Keep an instance variable, _stackConstraints . 保留一个实例变量_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];

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). 如果您愿意使用10.11+,则只需在Interface Builder中的NSStackView上选择“隐藏隐藏视图”(或通过编程在其上设置detachesHiddenViews detachesHiddenViews = YES )。

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). 然后将View#1设置为hidden = YES将自动重新布局堆栈视图,从而使View#2占用更多空间(假设堆栈视图的高度是固定的–否则,堆栈视图的高度将变小)。


If you need to support 10.10 or earlier, then you can hide the view this way: 如果需要支持10.10或更早版本,则可以通过以下方式隐藏视图:

[stackView setVisibilityPriority:NSStackViewVisibilityPriorityNotVisible forView:view1];

And show it again via: 并通过以下方式再次显示:

[stackView setVisibilityPriority:NSStackViewVisibilityPriorityMustHold forView:view1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM