自动布局如何在具有 3 个等宽视图的视图中隐藏 1 个视图 [英] Auto layout how to hide 1 view in a view with 3 equal width views

查看:30
本文介绍了自动布局如何在具有 3 个等宽视图的视图中隐藏 1 个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我在 1 个视图中有 3 个视图(固定到超级视图的前沿和后沿).

Currently I have 3 views inside 1 view (which is pinned to leading edge and trailing edge of superview).

这 3 个视图目前如下所示:

The 3 views look like this currently:

但是,在某些情况下,我希望隐藏靛蓝视图,但仍保持最后 2 个相同的宽度,如下所示:

However, in some cases, I wish to hide the indigo view, but still keep the last 2 the same widths like so:

如何通过自动布局实现这一点?或者如何使用 IBOutlets 进行约束来实现这一点?

How can I achieve this with autolayout? Or how can I achieve this using IBOutlets for constraints?

推荐答案

如果部署目标是iOS9或更高版本,建议使用UIStackView作为封闭视图.在 UIStackView 中排列的任何视图上将 isHidden 设置为 true 不仅会使视图隐藏,而且堆栈视图也会重新组织所有视图非隐藏视图填充隐藏视图占用的空间.可以通过调整 UIStackView 上的 distribution 来调整此行为.

If the deployment target is iOS9 or later, it is recommended to use UIStackView as the enclosing view. Setting isHidden to true on any view arranged in the UIStackView will not only make the view hidden, but also will the stack view re-organize all the non-hidden views to fill up the space that was taken by the hidden views. This behavior could be tuned by adjusting distribution on UIStackView.

Tj3n 的答案有效,但它有一个缺点,您必须在代码中使用幻数并在代码和 IB 中设置约束属性.

Tj3n's answer works, but it has a drawback that you have to use magic numbers in your code and set constraint properties both in code and IB.

恕我直言,更好的解决方案是在 IB 中设置具有不同优先级的所有约束,并在代码中激活/停用它们.试试这个:

IMHO, a better solution would be setting up all the constraints in IB with different priorities and activating/deactivating them in code. Try this:

  1. 像以前一样设置前导/尾随约束.
  2. 为所有三个优先级high的视图设置等宽约束.
  3. 为所有三个优先级required的视图设置0宽度约束,但在IB中将它们停用.并将它们连接到代码中的 IBOutlet,就像连接视图一样.
  4. 激活任何 0 宽度约束以折叠您想要的视图,然后停用它们以展开.
  1. Set the leading/trailing constraints as you did before.
  2. Set equal width constraints for all three views with priority high.
  3. Set 0 width constraints for all three views with priority required, but leave them deactivated in IB. And connect them to IBOutlets in code just as connecting views.
  4. Activate any of the 0 width constraints to collapse the view you want, and later deactivate them to expand.

注意,只要设置 1 和 2,就可以实现等宽视图布局.使用 3 和 4,您可以有选择地折叠/展开任何视图.

Note that just with 1 and 2 in place, you can achieve the equal-width view layout. And with 3 and 4, you can collapse/expand any of the views selectively.

这篇关于自动布局如何在具有 3 个等宽视图的视图中隐藏 1 个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆