【发布时间】:2016-05-28 22:23:59
【问题描述】:
我在故事板编辑器的UIViewController 中添加了一个UILabel (amountLabel)。然后在快速文件viewDidLoad 中,我以编程方式创建UITextField (paymentTextField) 并尝试在amountLabel 和paymentTextField 之间添加约束。这是我在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'而终止应用程序, 原因:'无法使用项目 > 和 > 激活约束,因为它们没有共同的祖先。 约束是否引用不同视图层次结构中的项目? 这是违法的。”
有谁知道怎么回事? amountLabel 被直接拖到情节提要中的视图中,并且“paymentTextField”以编程方式添加到同一视图中。为什么他们没有共同的祖先?
【问题讨论】: