Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flipping the positions of items in a UIStackView

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

like image 778
ilikecode Avatar asked Jan 22 '18 07:01

ilikecode


3 Answers

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.

like image 63
Hapeki Avatar answered Oct 18 '22 10:10

Hapeki


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

like image 33
Jaydeep Vora Avatar answered Oct 18 '22 09:10

Jaydeep Vora


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

like image 29
Elmar Schoettner Avatar answered Oct 18 '22 10:10

Elmar Schoettner