我在这个问题上工作了 2 天,却不了解它背后的思想... 所以为了快速解释,我在另一个 Storyboard中创建了一个基于 Nib 的 View ,如下所示:
let storyboard = UIStoryboard(name: "TestNib", bundle: nil)
testNib = storyboard.instantiateViewControllerWithIdentifier("TestNib") as! TestNib
testNib.view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(testNib.view)
然后我使用 constraintsWithVisualFormat 手动添加一些约束,如下所示:
constraint_V = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-(10)-[conversationMenu(300)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views: ["conversationMenu": testNib.view])
let constraint_H = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[conversationMenu]|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views: ["conversationMenu": testNib.view])
self.view.addConstraints(constraint_V)
self.view.addConstraints(constraint_H)
没问题,一切正常。 (顺便说一句,我也尝试在 Storyboard中查看)。
主要问题是当我想为这个 View 设置动画时,“testNib”(self.view.addSubview(testNib.view)) 中的约束中断了。这发生在我在 ViewDidAppear 中创建 constraintsWithVisualFormat 时。在 ViewDidLoad 中,一切都完美地工作......
这是我实例的变量:
var testNib: TestNib!
var constraint_V: [NSLayoutConstraint]!
var completion = false
这是我为约束设置动画的代码:
if completion == false {
for constraint in constraint_V {
if constraint.firstAttribute == NSLayoutAttribute.Top {
constraint.constant = -200
}
}
} else {
for constraint in constraint_V {
if constraint.firstAttribute == NSLayoutAttribute.Top {
constraint.constant = 10
}
}
}
completion = !completion
UIView.animateWithDuration(1, animations: {
self.view.layoutIfNeeded()
}, completion: {(value: Bool) in
})
你会问我,如果它在 ViewDidLoad 中有效,你为什么不使用它? 这是因为我的主要问题是当我“presentViewController”并关闭它时,约束再次中断,我发现重现此错误的唯一方法是将我的初始化插入 ViewDidAppear。
如果你想和我一起测试,我已经提交并将我的代码推送到 github 中:https://github.com/Comanga/Bug-Constraints .
您需要看到的是不再受制于顶部约束的绿色 View 。
哦,你读到这一行了吗?谢谢<3
iOS9-SWIFT 2.0
最佳答案
希望对你有帮助
viewDidAppear is called finally after UIKit laid out sub views and displayed them.
所以它不起作用,您可以想出另一种方法在添加/删除约束后重新布局 View Controller 。
试试 setNeedsUpdateConstraints 什么的
关于IOS 错误约束 ViewDidAppear 与 ViewDidLoad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33164569/