Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

ios - Auto layout how to hide 1 view in a view with 3 equal width views

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

The 3 views look like this currently:

3 views with equal widths

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'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.

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. 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...