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..." } }
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.
I suggest you to not add constraints in viewDidLoad, because the view hierarchy is set, but not constraints. You should prefer updateViewConstraints or viewWillLayoutSubviews
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With