62

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..."
    }
}
mustafa
  • 15,254
  • 10
  • 48
  • 57

4 Answers4

86

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.

knuku
  • 6,082
  • 1
  • 35
  • 43
  • 5
    I had a similar crash but the view was created within the code. And indeed I was add constraints before adding the view. If your view is already in the storyboard, could you add the constraints directly there? – Kevin Delord Apr 26 '15 at 10:09
12

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

vmeyer
  • 1,998
  • 21
  • 23
  • 6
    This answer is good since adding constraints in didLoad or will/DidAppear can crash the app due to view hierarchy unprepared for this. – MacMark Sep 14 '16 at 06:59
5

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

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

Aakash Gupta
  • 184
  • 3
  • 9
1

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

Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58