Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save felix-schwarz/417ece0fd3001d4831fc to your computer and use it in GitHub Desktop.
Save felix-schwarz/417ece0fd3001d4831fc to your computer and use it in GitHub Desktop.
+[UIViewController attemptRotationToDeviceOrientation] does what it says on the tin: attempt to rotate to the device's orientation. It does, however, not rotate the view controller to match -[UIViewController supportedInterfaceOrientation] when the current device orientation is not supported by the view controller it polls. I whipped together th…
UIDeviceOrientation actualDeviceOrientation = [[UIDevice currentDevice] orientation];
BOOL changedDeviceOrientation = NO;
if ((self.supportedInterfaceOrientations & (UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight)) == 0)
{
if (UIScreen.mainScreen.bounds.size.width > UIScreen.mainScreen.bounds.size.height) // Device is in landscape orientation
{
[[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
changedDeviceOrientation = YES;
}
}
[UIViewController attemptRotationToDeviceOrientation];
if (changedDeviceOrientation)
{
[[UIDevice currentDevice] setValue:@(actualDeviceOrientation) forKey:@"orientation"];
}
@frankosterfeld
Copy link

Just a note, as I was using this snippet for some years: It stopped working in iOS 16, apparently orientation was readonly to begin with, and setValue working was a bug that is now fixed in iOS 16.

What works in iOS 16 is to call setNeedsUpdateOfSupportedInterfaceOrientations() (new in iOS 16) on the UIViewController.

So what I do is

if ([self respondsToSelector:@selector(setNeedsUpdateOfSupportedInterfaceOrientations)]) {
    // new way in iOS >= 16
    [self setNeedsUpdateOfSupportedInterfaceOrientations];
} else {
    // old way, iOS <= 15
   ... do like in the snippet above
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment