11

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 :).

ilikecode
  • 391
  • 3
  • 14
  • How about changing semantic to .forceRightToLeft. That's an easy and quick but not a good fix. – Jamil Jul 15 '20 at 08:11

3 Answers3

18

Create a layout with 2 UIViews in a UIStackView like so:

layout

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:

enter image description here

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.

Hapeki
  • 2,153
  • 1
  • 20
  • 36
12

You can change the view semantic of UIStackView from Unspecified to Force Right-to-Left to swap the position of of nested view.

Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
4

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