Stackview exchange or change order of views

2020-06-09 07:45发布

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)

3条回答
对你真心纯属浪费
2楼-- · 2020-06-09 08:07

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];
查看更多
乱世女痞
3楼-- · 2020-06-09 08:12

Try this bunch of code for replacing views in UIStackView, without refreshing any layouts.

if let objView = stackView.arrangedSubviews.first {
        objView.removeFromSuperview()
}
stackView.insertArrangedSubview(yourView, at: 0)
查看更多
疯言疯语
4楼-- · 2020-06-09 08:26

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()
}
查看更多
登录 后发表回答