Question

new iOS developer here. I have multiple views that require different images to be displayed in portrait and landscape. I currently have implemented that successfully and the portrait image loads fine, and, upon rotation, the landscape image also loads fine. However, if the device is in landscape orientation then switches to another view, it loads improperly - wrong size, resolution, alignments, etc. My code for dealing with orientation changes is below:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
    {
        if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
        {
            _image1.image = [UIImage imageNamed:@"Landscape.png"];
        }
        else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
        {
            _image1.image = [UIImage imageNamed:@"Portrait.png"];
        }
}

I believe it is because the method is only called upon rotation. If I rotate the improper, initial landscape view, for instance, it displays the correct images once again. Is there a way to get the method to run and load the proper landscape view when the initial orientation is in landscape? Or a way to force the correct image to display? Thanks much.

Was it helpful?

Solution

I finally fixed this issue by adding an orientation checker. I added the following in my .h:

@property (nonatomic, readonly) UIDeviceOrientation *orientation;

Then I added this to my .m file in the viewDidLoad method:

if(([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {
_image1.image = [UIImage imageNamed:@"Landscape.png"];
}

This checks if the initial orientation is landscape. If it is, it loads my Landscape.png image. Otherwise, since the default image is my Portrait.png, as set in the Storyboard, that loads if the orientation is already in portrait. Cheers!

EDIT: The above code is not advised as you can run into issues when using it, such as with orientation-locked devices. I changed the it to check for the status bar's orientation, rather than the device's orientation, as below:

if(([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeLeft) || 
([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeRight)) { 
_image1.image = [UIImage imageNamed:@"Landscape.png"];
}

You do not need to declare any variables in the .h, and just add the above in the viewDidLoad method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top