4

I have UIStackView which contains 3 subviews. And it is created via storyboard.

What if I need in some cases replace the middle subview with another one? What is the best way to solve this issue without of recreating the whole stack view programmatically? Both objective-C and Swift solutions are applicable.

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49

2 Answers2

9

First, create an IBOutlet:

@IBOutlet weak var stackView: UIStackView!

...and then link the stack view to it from inside the storyboard.

To remove a view from your UIStackView, put:

stackView.removeArrangedSubview(yourView)

Then, you could add another view by doing:

stackView.insertArrangedSubview(anotherView, at: 1)
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
  • Thanks. What about the sizes? I mean if I replace view with another one of different size (in my case a button is replaced with a label and stack view is vertical) then it changes the size of the whole stack view. Should I set the height constraint of the all stack view subviews? – Vyachaslav Gerchicov Jun 19 '18 at 08:59
  • 1
    You need to set the button's height then. What you can also do is create all the views you'll need in the stack view inside the storyboard and then make them hidden which will remove them from the stack view. Later you can unhide it which will add it to the stack view again. This way you can easily design the all views in storyboard. – LinusGeffarth Jun 19 '18 at 09:03
  • 1
    And do not forget yourView.removeFromSuperview() after you remove your view from stack view – Abu-Bakr Jul 21 '21 at 10:49
0

Link the stackview to a file as an IBOutlet then you can access the arrangedViews inside it and replace the one in the middle of the array.

Tom Pearson
  • 384
  • 1
  • 8
  • Thanks. What about the sizes? I mean if I replace view with another one of different size (in my case a button is replaced with a label and stack view is vertical) then it changes the size of the whole stack view. Should I set the height constraint of the all stack view subviews? – Vyachaslav Gerchicov Jun 19 '18 at 08:59