在我的故事板应用程序中,我尝试向界面添加额外的 UITextField
.但我得到了标题所说的例外.我使用 SwiftAutoLayout 库.这是我的代码:
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..."
}
}
在绑定任何约束之前尝试将 passwordTextField
添加到其父视图.
Try adding passwordTextField
to its superview before binding any constraints to it.
UPD(感谢 @vmeyer 和 @MacMark):请注意,在 viewDidLoad
或 viewWillAppear
/viewDidAppear
但在 updateViewConstraints 或 viewWillLayoutSubviews 因为视图层次结构可能没有为此操作做好准备.
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.
这篇关于出现异常:“无法使用未准备好约束的视图层次结构设置布局"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!