I want to force the display orientation to portrait programatically as some other screens should still autorotate. I added some code that works but the screen still autorotates and is then quickly corrected when my code runs. I want to prevent the autorotation from occurring at all.
I'm running an SKView (SpriteKit) under SwiftUI using SpriteView. The code I have which works is:
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
This forces portrait mode. I found this on another stack overflow question which is now closed. According to that question, I should also have prevented autorotation. The example used the code below, however I think this only works on a UIView, not on an SKView. I can't find any way to get the code below to work. Code is:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
UIInterfaceOrientationMask.
return .portrait
}
override var shouldAutorotate: Bool {
return false
}
Can anyone explain how to disable autorotation with SpriteView and SKView?
In addition, is it still possible to read the actual orientation (portrait, portrait upside down, landscape left and landscape right) after the screen is forced into portrait? I need this information for some manual tweaking.
SwiftUI does not allow to block auto-rotation and
UIHostingControllerseems handle it explicitly inside independently of parent UIViewController settings or inherited controller blocks, so representable variant is also not possible (at least as container for SwiftUI content).A possible found workaround is to use compensate-rotation for view in response of orientation changes.
Here is demo. Tested with Xcode 13.4 / iOS 15.5