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:
method, or in updateViewConstraints
method?[self.view setNeedsUpdateConstraints];
, or layoutIfNeeded
, or setNeedsLayout
?How should I update, for example, the constant of a certain constraint:
self.myConstraint.constant = 30.0
or doing:
[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];
Thanks in advance
To schedule a change, call setNeedsUpdateConstraints() on the view. The system then calls your implementation of updateConstraints() before the layout occurs. This lets you verify that all necessary constraints for your content are in place at a time when your custom view's properties are not changing.
Sounds simple enough: whenever you need to change your layout, invalidate it. Then wait for the system to call updateConstraints() in the next layout pass, which is your chance to make the necessary changes to your layout constraints.
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
}
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
}];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With