当设备方向改变时,以编程方式更新约束的正确方法吗? [英] Correct way to programmatically update constraints when the device orientation changes?

查看:321
本文介绍了当设备方向改变时,以编程方式更新约束的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用storyboardautolayout,并在相应的视图控制器中将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:

  1. 我应该在-viewWillTransitionToSize:withTransitionCoordinator:方法中还是在updateViewConstraints方法中设置新约束?
  2. 设置新的约束后,我应该叫[self.view setNeedsUpdateConstraints];还是layoutIfNeededsetNeedsLayout?
  3. 例如,应该如何更新某个约束的常数:

  1. Should I set the new constraints in -viewWillTransitionToSize:withTransitionCoordinator: method, or in updateViewConstraints method?
  2. When the new constraints are set, should I call [self.view setNeedsUpdateConstraints];, or layoutIfNeeded, or setNeedsLayout?
  3. 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
    }];
}

这篇关于当设备方向改变时,以编程方式更新约束的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆