Getting Exception: quot;Impossible to set up layout with view hierarchy unprepared for constraintquot;(出现异常:“无法使用未准备好约束的视图层次结构设置布局)
问题描述
在我的故事板应用程序中,我尝试向界面添加额外的 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.
这篇关于出现异常:“无法使用未准备好约束的视图层次结构设置布局"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:出现异常:“无法使用未准备好约束的视图层次结构设置布局"
基础教程推荐
- 如何从 logcat 中删除旧数据? 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
