Search code examples
objective-cswiftreplacesubviewuistackview

Replace view inside UIStackView?


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.


Solution

  • 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)