I know Auto Layout can be used to make the sizes and position consistent when the orientation changes. Is it possible to completely change the layout when the orientation change
I've had the same problem and here's what I've found so far. The approach I'm using is having two sets (potentially multiple) sets of constraints for different screen sizes or orientations. So I just design for portrait and connect all constraints that are portrait-specific to a IBOutletCollection: Then switch the VC orientation in InterfaceBuilder to Landscape and add the required constraints for this orientation and connect to the corresponding outlet:
Then in code I'm removing or adding the constraints as required:
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
[self updateViewConstraints];
}
- (void)updateViewConstraints
{
[super updateViewConstraints];
if (self.view.frame.size.width >= kSize * 2 + kPadding * 3)
{
[self.view removeConstraints:self.constraintsForPortrait];
[self.view addConstraints:self.constraintsForLandscape];
} else
{
[self.view removeConstraints:self.constraintsForLandscape];
[self.view addConstraints:self.constraintsForPortrait];
}
}
You can achieve similar results with this code, basing your adding/removing of constraints on orientation instead of frame size:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[self updateViewConstraints];
}
But keeping in mind that Apple is rumored to release devices with different screen aspect ratios and obsoleting the UIInterfaceOrientation and rotation events, it might be worth preparing in advance. Will see what future brings.
The downside of the approach is that that Xcode will be complaining about the design being ambiguous, which it actually is, since Xcode doesn't know we'll be removing the ambiguity at runtime. To tackle that you could set the priority of the constraints to be optional for all other orientations that you're not designing for at this particular moment (e.g. if you're designing for Portrait then optionalize the constraints for Landscape).