I added 3 subviews to UIStackView in storyboard. Problem is I need to add a fourth subview which overlaps with the second subview. Only one of the two overlapping subviews will be visible at a time. Is it easy to specify in Storyboard, or I need to add and remove subviews in code?
To switch between the 2nd or 4th subview on your UIStackView
you don't need to add or remove subviews, you just need to set the isHidden
property on them.
A stack view has an additional property arrangedSubviews
, these are the subviews that the stack view will manage the layout of. If you set isHidden
to true
and check the arrangedSubviews
property you'll see the hidden view has a height
of 0
. If you check the view debugger, the hidden view is not visible at all in the view hierarchy. The stack view will layout the remaining views according to the properties of the stack view.
This is slightly different to normal views where if a subview's isHidden
property becomes true, the subview still participates in the view's layout, the contents are just not drawn and it doesn't receive input events.