The correct way to programmatically update restrictions when changing device orientation?

I use storyboard and autolayout and set limits in IB as an IBOutlet in the appropriate view controller. I am reading a few posts on how to update restrictions that may differ from portrait and landscape, but I'm still not sure how to do this:

  • Should I set new restrictions in the -viewWillTransitionToSize:withTransitionCoordinator: method or in the updateViewConstraints method?
  • When new restrictions are set, I should call [self.view setNeedsUpdateConstraints]; or layoutIfNeeded , or setNeedsLayout ?
  • How to update, for example, a constant of a certain restriction:

    self.myConstraint.constant = 30.0

or execute:

 [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]; 

Thank you in advance

+6
source share
3 answers

A change in orientation will be detected using the viewWillTransitionToSize method. This method will be called when the orientation of the device changes.

 -(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator (id<UIViewControllerTransitionCoordinator>)coordinator{ //change constraints } 

Alternatively, if you want to change the constraints after changing the orientation, use the animateAlongsideTransition coordinator object in the viewWillTransitionToSize method.

 -(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{ [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { //change constraints }]; } 
+1
source

It would be best to change the constant instead of removing the constraint and re-creating it again. Simply adding or subtracting from a constant is much faster in the long run. What you would like to do is something like:

 [self.view layoutIfNeeded]; self.myConstraint.constant = 30.0; [self.view layoutIfNeeded]; 

It is recommended that you call layoutIfNeeded before and after changing the constant. This is because you may have some kind of restriction that has not yet been done, and do it before changing more restrictions.

0
source

A better idea would be to use Size Classes in Interface Builder to achieve autorotation changes.

https://www.codefellows.org/blog/size-classes-with-xcode-6-one-storyboard-for-all-sizes

0
source

All Articles