How do I detect a rotation on the iPhone without the device autorotating?

13,365

Solution 1

You can register for the notification UIDeviceOrientationDidChangeNotification (from UIDevice.h), and then when you care about orientation changes call this method:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

When you no longer care about orientation changes, call this method:

[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

The notification will be sent when applicable, and you can check [UIDevice currentDevice].orientation to find out what the current orientation is.

Solution 2

On a side note shouldAutoRotateToInterfaceOrientation used to be called on the time for rotation in 2.x, but in 3.0 it's much less consistent. The notification mentioned in the other post is the way to go for reliable indication of rotation.

Solution 3

You're returning YES from shouldAutorotateToInterfaceOrientation:, which I suspect you didn't mean to do. That's the only method you need to implement to prevent the device from rotating.

As for getting the current orientation of the device, you can use [[UIDevice currentDevice] orientation].

Share:
13,365
Nick Cartwright
Author by

Nick Cartwright

Updated on June 05, 2022

Comments

  • Nick Cartwright
    Nick Cartwright almost 2 years

    Anyone know how to do this?

    I thought this:

    -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        return YES;
    }
    
    - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    }
    
    - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
    }
    
    - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    }
    
    - (void)willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    }
    
    - (void)didAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    }
    
    - (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration {
    }
    

    may prevent the device from rotation (overriding all rotate methods of my UIViewController and not calling the superclass) but I fear it's not the UIViewController that actually performs the rotation.

    My UIViewController is in a UINavigationController.

    Anyone have any ideas?

    Cheers, Nick.