快速以编程方式添加约束 [英] Swift add constraint programmatically

查看:87
本文介绍了快速以编程方式添加约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在情节提要编辑器中的UIViewController中添加了UILabel(amountLabel).然后在快捷文件viewDidLoad中,我以编程方式创建了UITextField(paymentTextField),并尝试在amountLabelpaymentTextField之间添加约束.这是我在viewDidload中的代码:

I add a UILabel (amountLabel) in UIViewController in storyboard editor. And then in swift file, viewDidLoad, I programatically create a UITextField (paymentTextField) and try to add a constraint between amountLabel and paymentTextField. Here is my code in viewDidload:

let paymentTextField = UITextField()
    paymentTextField.translatesAutoresizingMaskIntoConstraints = false
    paymentTextField.frame = CGRectMake(15, 100, CGRectGetWidth(self.view.frame) - 30, 44)
    self.view.addSubview(paymentTextField)

    let bottonConstraint = NSLayoutConstraint(item: paymentTextField, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.amountLabel , attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 30)
    bottonConstraint.identifier = "paymentTextFieldSpacing"
    NSLayoutConstraint.activateConstraints([bottonConstraint])

但是我得到一个错误:

由于未捕获的异常'NSGenericException'而终止应用程序, 原因:无法激活具有>和>的约束,因为它们没有共同的祖先. 约束是否引用了不同视图层次结构中的项目? 那是非法的."

"Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with items > and > because they have no common ancestor. Does the constraint reference items in different view hierarchies? That's illegal."

有人知道出什么问题了吗?将amountLabel直接拖动到情节提要中的视图,并以编程方式将"paymentTextField"添加到同一视图.为什么他们没有共同的祖先?

Does anyone know what is wrong? amountLabel is directly dragged to the view in storyboard and "paymentTextField" is added programmatically to the same view. Why have they no common ancestor?

推荐答案

我遇到了与您先前描述的相同的问题.为了制作程序化子视图(在您的情况下为paymentTextField),您必须先将其添加到子视图中,然后再应用约束.

I ran into the same problem that you described earlier. In order to make the programmatic subview, (in your case the paymentTextField) you have to add this to the subview first and then apply your constraints.

通过首先添加子视图以确保两个视图具有相同的父视图.

By adding the subview to view first, this ensures both views have the same parent.

这篇关于快速以编程方式添加约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆