我在界面构建器中有一个约束,它有一个默认值和一个紧凑的宽度值。我将此约束链接到IBOutlet,因此我可以在运行时获取代码中的常量值。如果我在iPhone 4S模拟器上运行,则在viewDidLoad
中,常量是默认值。调用willTransitionToTraitCollection
或viewWillTransitionToSize
都不会被调用,但在某些时候,约束会更新为紧凑值,因为稍后它是正确的。约束在哪里由UIViewController
更新?这不是updateViewConstraints
。
更新:建议的viewDidLayoutSubviews
和traitCollectionDidChange
方法不是常量更改的位置:
override func viewDidLayoutSubviews() {
println("Before viewDidLayoutSubviews: \(self.navControllerBottomSpaceConstraint.constant)")
super.viewDidLayoutSubviews()
println("After viewDidLayoutSubviews: \(self.navControllerBottomSpaceConstraint.constant)")
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
println("Before traitCollectionDidChange: \(self.navControllerBottomSpaceConstraint.constant)")
super.traitCollectionDidChange(previousTraitCollection)
println("After traitCollectionDidChange: \(self.navControllerBottomSpaceConstraint.constant)")
}
输出:
Before viewDidLayoutSubviews: 20.0
After viewDidLayoutSubviews: 20.0
Before viewDidLayoutSubviews: 20.0
After viewDidLayoutSubviews: 20.0
Before viewDidLayoutSubviews: 20.0
After viewDidLayoutSubviews: 20.0
Before viewDidLayoutSubviews: 20.0
After viewDidLayoutSubviews: 20.0
Before traitCollectionDidChange: 20.0
After traitCollectionDidChange: 20.0
Before viewDidLayoutSubviews: 0.0
After viewDidLayoutSubviews: 0.0
Before viewDidLayoutSubviews: 0.0
After viewDidLayoutSubviews: 0.0
答案 0 :(得分:1)
感谢Matt和Sega-Zero指出我正确的方向。
答案是约束在进入视图层次结构后在视图的第一个layoutSubviews
中更新。所以在你的视图控制器中你可以这样做:
override func viewDidLayoutSubviews() {
if self.propertyCalculatedFromConstraints == nil && self.view.window != nil {
// constraints and sizes are now valid
self.propertyCalculatedFromConstraints = self.constraint.constant
}
super.viewDidLayoutSubviews()
}
override func viewDidDisappear() {
self.propertyCalculatedFromConstraints = nil
super.viewDidDisappear()
}
答案 1 :(得分:0)
traitCollectionDidChange:是您可以捕捉大小类更改的地方,或者父视图的viewDidLayoutSubviews
是您可以检测到任何自动布局更改的地方