UIDevice orientation keeps flipping between UIDeviceOrientationPortrait and UIDeviceOrientationLandscapeRight when I put my phone flat

StackOverflow https://stackoverflow.com/questions/20822114

  •  22-09-2022
  •  | 
  •  

Question

I'm quite confused about the device orientation value when I put my phone flat. I registered a observer for UIDeviceOrientationDidChangeNotification, and called beginGeneratingDeviceOrientationNotifications to observer device orientation change. Everything works fine until I put my phone flat on desktop.

Here's the code in my project:

- (void)deviceDidRotate:(NSNotification *)notification
{
    UIDevice *currentDevice = [UIDevice currentDevice];
    NSLog(@"Orientation: %d", currentDevice.orientation);
}

And the log gives me this:

2013-12-29 12:14:28.121 MyProject[1140:60b] Orientation: 5
2013-12-29 12:14:28.764 MyProject[1140:60b] Orientation: 1
2013-12-29 12:14:31.609 MyProject[1140:60b] Orientation: 4
2013-12-29 12:14:33.377 MyProject[1140:60b] Orientation: 1
2013-12-29 12:14:33.574 MyProject[1140:60b] Orientation: 4
2013-12-29 12:14:33.770 MyProject[1140:60b] Orientation: 1
2013-12-29 12:14:33.868 MyProject[1140:60b] Orientation: 4
2013-12-29 12:14:34.065 MyProject[1140:60b] Orientation: 1
2013-12-29 12:14:34.164 MyProject[1140:60b] Orientation: 4
2013-12-29 12:14:34.455 MyProject[1140:60b] Orientation: 1
2013-12-29 12:14:34.555 MyProject[1140:60b] Orientation: 4
    repeating...

The first 5 is quite reasonable, since I've put my phone face up, but the 1s (represent UIDeviceOrientationPortrait) and 4s (represent UIDeviceOrientationLandscapeRight) are quite confusing.

My question is how to fix this problem?

Was it helpful?

Solution

I had a same problem, following solution fixed this issue:

Add following methods in each viewController (with your preferred orientation)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

- (BOOL)shouldAutorotate {

    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {

    return UIInterfaceOrientationMaskLandscape;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {

    return UIInterfaceOrientationLandscapeLeft;
}

and in AppDelegate as well with following line of code in didFinishLaunchingWithOptions

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preferredInterfaceOrientationForPresentation) name:@"UIDeviceOrientationDidChangeNotification" object:nil];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top