Skip to content

Instantly share code, notes, and snippets.

@coolio107
Last active November 17, 2017 05:54
Show Gist options
  • Save coolio107/f843789e5225c1f6fc9b to your computer and use it in GitHub Desktop.
Save coolio107/f843789e5225c1f6fc9b to your computer and use it in GitHub Desktop.
relativeInterfaceOrientationFromRotationAngle class extension for UIViewController
- (UIInterfaceOrientation)relativeInterfaceOrientationFromRotationAngle:(CGFloat)angle {
NSArray * conversionMatrix = @[ @(UIInterfaceOrientationPortrait),
@(UIInterfaceOrientationLandscapeRight),
@(UIInterfaceOrientationPortraitUpsideDown),
@(UIInterfaceOrientationMaskLandscapeLeft)];
NSInteger oldIndex = [conversionMatrix indexOfObject:@(self.interfaceOrientation)];
if (oldIndex == NSNotFound)
return UIInterfaceOrientationUnknown;
NSInteger newIndex = (oldIndex - (NSInteger)roundf(angle / M_PI_2)) % 4;
while (newIndex < 0) {
newIndex +=4;
}
return [conversionMatrix[newIndex] intValue];
}
@coolio107
Copy link
Author

This is a class extension for UIViewController that translates a rotation angle (from the current orientation) into a new orientation value as needed to translate a rotation as provided by a transition coordinator to a new interface orientation as used by legacy APIs.

@sstadelman
Copy link

Swift 4 conversion

    func relativeInterfaceOrientation(from rotationAngle: CGFloat) -> UIInterfaceOrientation {
        let conversionMatrix: [UIInterfaceOrientation] = [.portrait, .landscapeRight, .portraitUpsideDown, .landscapeLeft]
        guard let oldIndex = conversionMatrix.index(of: self.interfaceOrientation), oldIndex != NSNotFound else {
            return .unknown
        }
        var newIndex = Int(oldIndex) - Int(round(rotationAngle / .pi).truncatingRemainder(dividingBy: 4))
        while newIndex < 0 {
            newIndex += 4
        }
        return conversionMatrix[newIndex]
    }

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