How to get device orientation via UIView link?

I need to get device orientation from ViewController. I can not be based on :

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

since it sometimes returns an unknown orientation (for example, when the device is in the table).

I just need to know in which orientation my current UIView is displayed (is it a landscape on the left or right). I do not need to update this value when the orientation changes, I just want to know when I ask about it. Only some links are view.orientation;). Is there something that will help me? I read the UIView documentation, found a link to UIWindow, but nothing that could help me.

+5
source share
4 answers

UIApplication,

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
+13

UIViewController

UIInterfaceOrientation interfaceOrientation;

, UIViewController

UIInterfaceOrientation myCurrentOrientation = self.interfaceOrientation;
+4

Quick version

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


    if currentOrientation.isPortrait {

        print("PORTRAIT")

    } else if currentOrientation.isLandscape {

        print("LANDSCAPE")

    }
0
source

Below is sample code to do the same. There is a variable called deviceOrientation , and it will respond to the current device orientation with every request.

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;
}
-1
source

All Articles