Getting Exception: “Impossible to set up layout with view hierarchy unprepared for constraint”

i0S Swift Issue

Question or problem with Swift language programming:

In my storyboard application I try to add extra UITextField to interface. But I get the exception that title says. I use SwiftAutoLayout library. Here is my code:

// MARK: - IBOutlets

@IBOutlet weak var passwordTextField: UITextField!

// MARK: - Properties

let userIdTextField = UITextField()

// MARK: - Lifecycle

override func viewDidLoad() {
    super.viewDidLoad()

    self.passwordTextField.keyboardType = .NumberPad

    if getCurrentUserId() == nil {
        self.view.addSubview(userIdTextField)
        userIdTextField.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addConstraints([userIdTextField.al_leading == passwordTextField.al_leading,
            userIdTextField.al_trailing == passwordTextField.al_trailing,
            userIdTextField.al_top == passwordTextField.al_bottom + 8])
        userIdTextField.placeholder = "Enter User Id..."
    }
}

How to solve the problem:

Solution 1:

Try adding passwordTextField to its superview before binding any constraints to it.


UPD (thanks @vmeyer and @MacMark): please notice that it’s safer to add constraints not in viewDidLoad or viewWillAppear/viewDidAppear but in updateViewConstraints or viewWillLayoutSubviews since the view hierarchy might be unprepared for this operation.

Solution 2:

I suggest you to not add constraints in viewDidLoad, because the view hierarchy is set, but not constraints.
You should prefer updateViewConstraints or viewWillLayoutSubviews

Solution 3:

You are trying to adding constraint to view which is not added/created in current view hierarchy. First add view then apply constraint.

Solution 4:

Please add the view to superview before adding constraints for the view in superview.

superView?.addSubview(view)
superView?.addConstraints([topConstraint,leftConstraint,bottomConstraint,rightConstraint])

Hope this helps!