简体   繁体   English

如何使用Swift以编程方式移动UIView并放置新的UIView?

[英]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. 我想在屏幕顶部放置一个UIView(UILabel,UITextField ...),然后将布局向下移动,但是我不知道该怎么做,我看到了一些文档和教程,但对我没有帮助。 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. 现在,编辑高度约束并将其常数设置为0。这会将该视图折叠为0高度,使其消失,其他视图向上移动。

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. 然后,在代码中,当您希望显示“此处的其他视图”视图时,使用出口将该视图上的常量设置回其先前的非零值,然后在父视图上调用layoutIfNeeded()进行更新基于更改的约束的视图布局。

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. 通过调整视图的高度约束,您可以轻松地来回显示/隐藏它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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