Skip to content

Instantly share code, notes, and snippets.

@macguru
Created April 11, 2018 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save macguru/c52558fbb7475ecc13f3348e5a81ef96 to your computer and use it in GitHub Desktop.
Save macguru/c52558fbb7475ecc13f3348e5a81ef96 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