问题描述
我正在使用storyboard
和autolayout
,并在相应的视图控制器中将IB中的约束设置为IBOutlet
.我正在阅读几篇有关如何更新纵向和横向约束的文章,但我仍然不确定该怎么做:
I'm using storyboard
and autolayout
, and setting the constraints in IB as IBOutlet
in the corresponding view controller. I'm reading several posts regarding how to update the constraints to be different in portrait and in landscape but I'm still not sure of how should I do this:
- 我应该在
-viewWillTransitionToSize:withTransitionCoordinator:
方法中还是在updateViewConstraints
方法中设置新约束? - 设置新的约束后,我应该叫
[self.view setNeedsUpdateConstraints];
还是layoutIfNeeded
或setNeedsLayout
? -
例如,应该如何更新某个约束的常数:
- Should I set the new constraints in
-viewWillTransitionToSize:withTransitionCoordinator:
method, or inupdateViewConstraints
method? - When the new constraints are set, should I call
[self.view setNeedsUpdateConstraints];
, orlayoutIfNeeded
, orsetNeedsLayout
? How should I update, for example, the constant of a certain constraint:
self.myConstraint.constant = 30.0
或这样做:
[self.view removeConstraint:self.passwordViewHeight];
self.passwordViewHeight = [NSLayoutConstraint constraintWithItem:self.passwordView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:34.0];
[self.view addConstraint:self.passwordViewHeight];
预先感谢
推荐答案
使用viewWillTransitionToSize方法检测方向更改.当设备方向即将改变时,将调用此方法.
Orientation change be detected using the method viewWillTransitionToSize. This method will be called when the device orientation is about to change.
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator (id<UIViewControllerTransitionCoordinator>)coordinator{
//change constraints
}
或者,如果要在方向更改后更改约束,请在viewWillTransitionToSize方法中使用协调器对象的animateAlongsideTransition方法.
Alternatively, if you want to change the constraints after the orientation changes, use the coordinator object's animateAlongsideTransition method in the viewWillTransitionToSize method.
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
[coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
//change constraints
}];
}
这篇关于当设备方向改变时,以编程方式更新约束的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!