简体   繁体   中英

How to shift UIView's and put a new UIView programmatically with Swift?

I've a layout with my data, but depending on data I need change the location of views. I wants put a UIView (UILabel, UITextField...) at top of screen and shift the layout to down, but I don't know how to do this, I saw some docs and tutorials but not helps me. I made my screen with storyboard.

This is original screen:

在此处输入图片说明

This is that I want:

在此处输入图片说明

My storyboard:

在此处输入图片说明

如果只想将视图添加到堆栈视图的顶部,请使用stackView.insertArrangedSubview(newView, at:0)

I would suggest setting up your screen with your "put other view here" in place, and a fixed height constraint on that view. Make the views below have a fixed space to the bottom of the "other view here view."

Then control-drag from the "put other view here"'s height constraint into your view controller. This will make the constraint an outlet.

Now edit the height constraint and set it's constant to 0. This will collapse that view to 0 height, causing it to disappear, and the other views to shift up.

Then, in code, when you want the "other view here" view to show up, use the outlet to set the constant on that view back to it's previous non-zero value, and then call layoutIfNeeded() on the parent view to update the view layouts based on changed constraints.

You could also write code that would insert your "other view here" view into the view hierarchy, but that would involve removing constraints and adding constraints in code, which is a bit of a pain.

By adjusting the height constraint on the view you can show/hide it back and forth with very little effort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM