简体   繁体   English

以编程方式快速更新约束

[英]swift update constraints programmatically

I have a UIView in which there are 4 components, UITextField , a UIActivityIndicator and 2 UIButtons . 我有一个UIView,其中有4个组件, UITextFieldUIActivityIndi​​cator和2个UIButtons All the components are using constraints set using storyboard. 所有组件都使用通过情节提要设置的约束。

Button1 UITextField UIActivityIndicator Button2 Button1 UITextField UIActivityIndi​​cator Button2

The UITextField displays the url of a UIWebView and the UIActivityIndicator corresponds to page loading. UITextField显示UIWebView的URL,而UIActivityIndi​​cator对应于页面加载。

When the page has loaded, UIActivityIndicator is hidden. 页面加载后, UIActivityIndi​​cator被隐藏。

What I want is that when the loading is complete and UIActivityIndicator is hidden, the size of UITextField increases and use up the space used by the UIActivityIndicator . 我想要的是,当加载完成并且UIActivityIndi​​cator隐藏时, UITextField的大小会增加并用完UIActivityIndi​​cator占用的空间。

Button1 UITextField Button2 Button1 UITextField Button2

Here's what I would do: 这就是我要做的:

Rather than putting a constraint between the text field and the activity indicator, use a constraint between the text field and it's superview, with extra padding added to make room for the activity indicator. 与其在文本字段和活动指示器之间放置一个约束,不如在文本字段及其父视图之间使用约束,并添加了额外的填充以为活动指示器留出空间。

Control-drag from the constraint into your view controller to create an outlet to it. 按住Control键将其拖到视图控制器中以为其创建出口。

In your code, when you hide the activity indicator, reduce the constant setting on the constraint by the width of the activity indicator plus the space between the activity indicator and the text field so that the text field gets wider to fill the space that's freed by the hiding of the activity indicator. 在您的代码中,当您隐藏活动指示器时,请通过活动指示器的宽度加上活动指示器与文本字段之间的空间来减小约束的常量设置,以使文本字段变宽以填充由活动指示器的隐藏。

If you want the text field to animate it's growth, put a call to layoutIfNeeded() in a call to UIView.animate(duration:animations:) immediately after the code that changes the constraint setting. 如果要使文本字段动画化,请在更改约束设置的代码之后立即调用UIView.animate(duration:animations:)中的layoutIfNeeded() That will cause the layout change to be animated. 这将使布局更改具有动画效果。

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

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