Flipping the positions of items in a UIStackView
Asked Answered
T

3

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

Tillford answered 22/1, 2018 at 7:26 Comment(1)
How about changing semantic to .forceRightToLeft. That's an easy and quick but not a good fix.Marinetti
U
19

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.

Unpaged answered 22/1, 2018 at 8:17 Comment(1)
what if i have 4-5 views inside stackview ?Flann
S
13

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

Stomachic answered 22/1, 2018 at 7:28 Comment(3)
teamOne.semanticContentAttribute = .forceRightToLeft doesn't seem to do anything for me, the result is the sameTillford
hStack.semanticContentAttribute = checkBoxOnRight ? .forceLeftToRight : .forceRightToLeft worked for in Xcode 12, Swift 5.2Phenacetin
Agreed with @Tillford this did absolutely nothing for me xCode 13.Phrasal
R
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

Roughhouse answered 22/1, 2018 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.