Aleksandar Djuric Aleksandar Djuric - 2 months ago 17
iOS Question

Constraining UITextField programmatically leads to error "Unable to activate constraint because they have no common ancestor."

I'm trying to programmatically constrain a UITextField but keep getting the error, "Unable to activate constraint with items because they have no common ancestor. Does the constraint reference items in different view hierarchies?".

I've narrowed the problem to the where I activate my constraint (i.e. constraint.active = true). However, I have no idea how to fix the problem.

While trying to debug, I found that printing out the textField.superview in my viewDidLoad() or viewWillAppear() reports back a nil even though I add the textField subview to view in the line before. Finally, if I just initialize the textField with a CGRect it works perfectly. Just can't add contraints.

This ones got me really stumped.

class SignInController: UIViewController {

var emailField: UITextField {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false

return textField
}

override func viewDidLoad() {
super.viewDidLoad()

view.addSubview(emailField)

setupEmailField()

print(view) //Returns <UIView: 0x7f93f6076510; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x7f93f607a8d0>>
print(emailField.superview) //Returns nil

}

// Breaks at this function
func setupEmailField() {

emailField.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 50).active = true
emailField.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -10).active = true
emailField.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 10).active = true
emailField.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: 0.05).active = true

}

Answer

You forgot to add the () to the end of your emailField declaration, so you created a computed property that returns a new, different UITextField each time you refer to the property. You want:

var emailField: UITextField {
    let textField = UITextField()
    textField.translatesAutoresizingMaskIntoConstraints = false
    return textField
}()
Comments