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

IosSwiftAutolayout

Ios Problem Overview


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..."
    }
}

Ios Solutions


Solution 1 - Ios

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 - Ios

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 - Ios

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

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

Solution 4 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmustafaView Question on Stackoverflow
Solution 1 - IosknukuView Answer on Stackoverflow
Solution 2 - IosvmeyerView Answer on Stackoverflow
Solution 3 - IosAakash GuptaView Answer on Stackoverflow
Solution 4 - IosGurjinder SinghView Answer on Stackoverflow