I have a UIStackView
initially set with 4 buttons. If I need to later swap out the last button with a new button or back to the initial button, how can I do that?
lazy var stackView: UIStackView = {
let sv = UIStackView()
sv.axis = .horizontal
sv.distribution = .fillEqually
sv.alignment = .fill
return sv
}()
// ...
var bt4: UIButton!
var bt5: UIButton!
// viewDidLoad
func configureStackView() {
view.addSubview(stackView)
stackView.addArrangedSubview(bt1)
stackView.addArrangedSubview(bt2)
stackView.addArrangedSubview(bt3)
stackView.addArrangedSubview(bt4)
// place stackView at bottom of scene
}
func swapLastButtonInStackViewWithNewButton(_ val: Bool) {
if val {
// if true replace bt4 in stackView with bt5
} else {
// if false replace bt5 in stackView with bt4
}
}
3
Answers
You can store the arrange of stack subviews like this:
and then
and finally implement the swap function like this:
This is not perfect, You can improve the code by your need.
UIStackView
automatically removes a view when this view is hidden. So basically all you have to do is to properly set theisHidden
boolean of button 4 and button 5.You can do this quite easily, without the need to keep a reference to
bt4
andbt5
:If you really want to keep a separate reference to the buttons, and add-to/remove-from the stack view, your can do this:
Here are complete examples…
First, using
.isHidden
approach:or, using a reference to
bt4
andbt5
and adding/removing them:Edit
The above code might seem a little overly complicated — but I think that’s more related to all of the setup and "extra" checks.
As a more straight-forward answer…
As long as you have setup your stack view and have valid references to
bt4
andbt5
, all you need to do is this:That will avoid the animation issues.