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

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:

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

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