How to get device orientation via UIView reference?
Asked Answered
C

4

6

I need to get device orientation from a ViewController. I cannot base on:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

because it sometimes returns orientation unknown (for example when the device lays on the table).

I just need to know in what orientation is my current UIView displayed (is it landscape left or landscape right). I don't need to have this value updated when orientation changes, I just want to know it, when I ask for it. Just some reference view.orientation ;). Is there something that would help me? I've read UIView documentation, found some reference to UIWindow, but nothing that could help me.

Corsage answered 26/4, 2012 at 12:26 Comment(0)
D
13

You can also get the device orientation from UIApplication, have you tried using

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
Disquiet answered 26/4, 2012 at 12:31 Comment(1)
That is exactly what I was looking for. Now I'm able to get UIKit components orientation and use it. Thanks a lot!Corsage
L
5

UIViewController has a property

UIInterfaceOrientation interfaceOrientation;

So in your UIViewController, you can access the current orientation of the device at any time via

UIInterfaceOrientation myCurrentOrientation = self.interfaceOrientation;
Lop answered 5/3, 2013 at 17:49 Comment(1)
Deprecated since iOS 8.0Goniometer
F
0

Swift Version

    let currentOrientation:UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation


    if currentOrientation.isPortrait {

        print("PORTRAIT")

    } else if currentOrientation.isLandscape {

        print("LANDSCAPE")

    }
Fairleigh answered 1/6, 2016 at 1:14 Comment(0)
T
-1

Following is the sample code to do the same. There is a variable named deviceOrientation, and it will answer the current orientation of device, whenever being asked.

UIDeviceOrientation deviceOrientation;

- (void)viewWillAppear:(BOOL)animated
{
    deviceOrientation = (UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation];
    [self willAnimateRotationToInterfaceOrientation:deviceOrientation duration:0.5];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
    deviceOrientation = (UIDeviceOrientation)interfaceOrientation;
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
        NSLog(@"Landscape");
    }
    else
    {
        NSLog(@"Portrait");
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return TRUE;
}
Tennant answered 26/4, 2012 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.