Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift add constraint programmatically

Tags:

ios

swift

iphone

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?

like image 269
jimshicard Avatar asked Feb 17 '16 09:02

jimshicard


1 Answers

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.

like image 169
Jamil Avatar answered Sep 25 '22 05:09

Jamil