Flipping the positions of items in a UIStackView

强颜欢笑 提交于 2020-01-03 16:54:12

问题


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


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/48376482/flipping-the-positions-of-items-in-a-uistackview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!