Skip to content

Instantly share code, notes, and snippets.

@munho
Forked from macguru/UIViewController+Rotation.m
Created January 11, 2021 01:57
Show Gist options
  • Select an option

  • Save munho/e642b0669917bc84c7f3a1f561e0ec4c to your computer and use it in GitHub Desktop.

Select an option

Save munho/e642b0669917bc84c7f3a1f561e0ec4c to your computer and use it in GitHub Desktop.
Forcing a rotation on a UIViewController.
//
// UIViewController+Rotation.m
// Ulysses
//
// Created by Götz Fabian on 12.10.17.
// Copyright © 2017 Ulysses GmbH & Co. KG. All rights reserved.
//
#import "UIViewController+Rotation.h"
NS_ASSUME_NONNULL_BEGIN
@implementation UIViewController (Rotation)
- (void)forcePreferredInterfaceOrientationIfNeeded
{
NSAssert(!self.isViewLoaded, @"Must not be called after loading the view.");
// Invalid orientation reported
UIDeviceOrientation deviceOrientation = UIDevice.currentDevice.orientation;
if (!UIDeviceOrientationIsValidInterfaceOrientation(deviceOrientation))
return;
// Interface orientation supported
UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)deviceOrientation;
UIInterfaceOrientationMask interfaceOrientationMask = (1 << interfaceOrientation);
if ((self.supportedInterfaceOrientations & interfaceOrientationMask) != 0)
return;
// Check if we can manually set orientation
NSString *selectorString = [NSString stringWithFormat: @"set%c%@", 'O', @"rientation:"];
if (![UIDevice.currentDevice respondsToSelector: NSSelectorFromString(selectorString)])
return;
NSAssert((self.supportedInterfaceOrientations & UIInterfaceOrientationMaskPortrait) == UIInterfaceOrientationMaskPortrait, @"Currently, only portrait is supported.");
// Force orientation change
[UIView performWithoutAnimation: ^{
[UIDevice.currentDevice setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
}];
}
@end
NS_ASSUME_NONNULL_END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment