Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stackview exchange or change order of views

Stackview containing array of textfield is embedded in scrollview. I want to change the order of the text fields on some actions. The way to remove and add the textfield results in distorted view. I also tested by removing from scrollview. Normal stackview too the exchange does not appear properly. I am using indexes to change :


stackView.removeArrangedSubview(localityTF) stackView.insertArrangedSubview(localityTF, at: 2)

like image 760
Ankish Jain Avatar asked Dec 26 '16 04:12

Ankish Jain


People also ask

When should I use stackView?

Best use of stack view is that if you want to set multiple controls allinged vertically or horizontally to each other you just add all of them in stack view. stackview will handle its allignment you just need to give frame contraints to stackView.

What are stack views?

Overview. Stack views let you leverage the power of Auto Layout, creating user interfaces that can dynamically adapt to the device's orientation, screen size, and any changes in the available space. The stack view manages the layout of all the views in its arrangedSubviews property.


2 Answers

It is strange behaviour, but problem with the autolayout system, that should be updated before you can add localityTF back. Also don't forget that removeArrangedSubview does not remove the view from subviews array:

[self.stackView removeArrangedSubview:_label1];
[self.stackView setNeedsLayout];
[self.stackView layoutIfNeeded];

[self.stackView insertArrangedSubview:_label1 atIndex:2];   
[self.stackView setNeedsLayout];
like image 135
Andrew Romanov Avatar answered Sep 27 '22 17:09

Andrew Romanov


This is my solution in Swift 3. It can also be used without defining the view in the stackview.

Here I am changing the locations of the views of a Stackview with two views:

if let myView = stackView.subviews.first {
    stackView.removeArrangedSubview(myView)
    stackView.setNeedsLayout()
    stackView.layoutIfNeeded()

    stackView.insertArrangedSubview(myView, at: 1)
    stackView.setNeedsLayout()
}
like image 39
Hilalkah Avatar answered Sep 27 '22 17:09

Hilalkah