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])
But I get an error:
"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."
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With