The usual way to do this is to have a different view controller for horizontal and present that view controller from your vertical VC with a cross-fade. There's more info about this in the View Controller Programming Guide under "Creating an Alternate Landscape Interface".
Replacing UIViews when screen rotates in the same View Controller
-
28-06-2022 - |
Question
I have never done this before - changing a ViewController´s UIView like this, so although it seems to be working perfectly I am unsure if this is a good idea - if it could lead to any major bugs. It uses Storybards but the viewLandscape
is loaded from nib
So I start off retaining a pointer to the current view in ViewDidLoad, I assume that the first view when viewDidLoad
is portrait, how can I be absolutely sure of this? then I initiallize the landscape view from nib.
// Assumes UIView loaded at start is portrait
self.viewPortrait = [[UIView alloc]initWithFrame:self.view.bounds];
self.viewPortrait = self.view;
UIView *landscapeView = [[[NSBundle mainBundle] loadNibNamed:@"LandscapeView" owner:self options:nil] objectAtIndex:0];
NSLog(@"view %@", landscapeView);
self.viewLandscape = [[UIView alloc]initWithFrame:landscapeView.bounds];
self.viewLandscape = landscapeView;
Now, I set which view to show according to the interface direction, pretty simple! but is it anything I should be aware of? One thing more, I have a label on the landscape view, how to I get a pointer to that label in this ViewController
(Pointer from the nib to the View Controller for the storyboard view)
-(void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"will rotate");
switch (toInterfaceOrientation)
{
case UIInterfaceOrientationPortrait:
case UIInterfaceOrientationPortraitUpsideDown:
self.view = self.viewPortrait;
break;
case UIInterfaceOrientationLandscapeLeft:
case UIInterfaceOrientationLandscapeRight:
self.view = self.viewLandscape;
break;
}
}
Solution