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:
- Set the leading/trailing constraints as you did before.
- Set equal width constraints for all three views with priority
high
.
- Set 0 width constraints for all three views with priority
required
, but leave them deactivated in IB. And connect them to IBOutlet
s in code just as connecting views.
- 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…