问题描述
在我的storyboard应用程序中,我尝试向界面添加额外的 UITextField
。但我得到标题所说的例外。我使用库。这是我的代码:
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
但在或,因为视图层次结构可能没有为此操作做好准备。
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.
这篇关于获得例外:“无法设置具有视图层次结构的布局,无法用于约束”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!