我在storyboard编辑器中添加了UILabel(amountLabel)UIViewController.然后在swift文件中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])
Run Code Online (Sandbox Code Playgroud)
但是我收到一个错误:
"由于未捕获的异常'NSGenericException'终止应用程序,原因:'无法激活带有项的约束>和>因为它们没有共同的祖先.约束是否引用不同视图层次结构中的项目?这是非法的."
有谁知道什么是错的?amountLabel直接拖到故事板中的视图,并以编程方式将"paymentTextField"添加到同一视图.为什么他们没有共同的祖先?