我正在使用storyboard和autolayout,并在IB中将约束设置为相应视图控制器中的IBOutlet.我正在阅读几篇关于如何更新纵向和横向不同的约束的帖子,但我仍然不确定我该怎么做:
>我应该在-viewWillTransitionToSize中设置新约束:withTransitionCoordinator:方法,还是在updateViewConstraints方法中?
>当设置新约束时,我应该调用[self.view setNeedsUpdateConstraints];,或layoutIfNeeded,还是setNeedsLayout?
>我应该如何更新,例如,某个约束的常量:
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方法检测方向更改.当设备方向即将改变时,将调用此方法.
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator (id<UIViewControllerTransitionCoordinator>)coordinator{ //change constraints }
或者,如果要在方向更改后更改约束,请在viewWillTransitionToSize方法中使用协调器对象的animateAlongsideTransition方法.
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{ [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { //change constraints }]; }