Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..."     } } 
like image 385
mustafa Avatar asked Oct 13 '14 21:10

mustafa


2 Answers

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.

like image 128
knuku Avatar answered Sep 23 '22 00:09

knuku


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

like image 35
vmeyer Avatar answered Sep 24 '22 00:09

vmeyer