I have a UIStackView
, created in Interface Builder
that contains two views. Now I'm trying to programatically change the order of these views (exchange their positions, so to speak).
Is there an easy fix for this that DOES NOT use Interface Builder to accomplish this?
Thanks :).
Create a layout with 2 UIViews
in a UIStackView
like so:
Create an outlet for your UIStackView
to your UIViewController
. Call addArrangedSubview
on your UIStackView
in viewDidLoad
to change the order. See snippet below.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Switches order of the stackView
stackView.addArrangedSubview(self.stackView.subviews[0])
}
}
This should be the result:
The addArrangedSubview
takes the given view and adds it to the end of the arrangedSubviews array. In our case we take the red view at index[0] and add it on the end (right) of the UIStackView
.
You can change the view semantic
of UIStackView from Unspecified
to Force Right-to-Left
to swap the position of of nested view.
you can use addArragnedSubview
to reorder the views.
Only addArragnedSubview is needed because when adding the view to a new parent it is removed from the old parent.
if self.viewsSwitched{
stackview.addArrangedSubview(self.stackview.subviews[0])
self.viewsSwitched = false
}else{
stackview.addArrangedSubview(self.stackview.subviews[1])
self.viewsSwitched = true
}
This code exchanges the two views inside the stackview by each call
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With