Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIDevice.current.setValue(value, forKey: "orientation") does not work if phone held in landscape and tilted 45 - 90 degrees

I'm using

let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")

to force the presenting view controller to show in landscape right. This is part of a navigation controller flow. This works as expected, but if the phone is held in landscape and titled between 45 and 90 degrees the view will present in portrait. The method is called and the expected value is correct, but no change to landscape occurs. This can be reproduced in a bare bones project with a navigation controller.

Does anyone have any idea what might cause this behavior?

like image 678
R.P. Carson Avatar asked May 26 '17 20:05

R.P. Carson


2 Answers

You could override

func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)

as described in https://developer.apple.com/reference/uikit/uitraitenvironment/1623516-traitcollectiondidchange

as in

- (void) traitCollectionDidChange: (UITraitCollection *) previousTraitCollection {
    [super traitCollectionDidChange: previousTraitCollection];
    if ((self.traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass)
        || (self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass)) {
        // your custom implementation here
    }
}

to maintain your orientation as desired. Alternatively, in XCode, click on your target, choose the General tab, and choose only one allowed orientation.

like image 69
mikep Avatar answered Sep 17 '22 02:09

mikep


Try this:

open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    get {
        return UIInterfaceOrientationMask.landscapeRight
    }
}

open override var shouldAutorotate: Bool {
    get {
        return false
    }
}

open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    get {
        return UIInterfaceOrientation.landscapeRight
    }
}

From @Dragos answer on Setting device orientation in Swift iOS

like image 28
elGeekalpha Avatar answered Sep 21 '22 02:09

elGeekalpha