2

I want to be able to rotate a modally presented view controller, but not rotate the view controller that presented it. I am controlling orientation changes in my app like this:

In my AppDelegate:

var orientationLock: UIInterfaceOrientationMask = .portrait

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return orientationLock
}

In my OrientationManager:

struct OrientationManager {
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }
}

In my ModallyPresentedViewController:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    OrientationManager.lockOrientation(.all)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    OrientationManager.lockOrientation(.portrait, andRotateTo: .portrait)
}

Currently this works, but it does rotate the modal view below it, which is why I have to call OrientationManager.lockOrientation(.portrait, andRotateTo: .portrait) when the view disappears. When the view disappears the presenting view controller is still rotated for a few seconds before it moves back to being in portrait mode. How can I prevent the presenting view controller from rotating? Thanks!

(Side note, does anyone know if UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation") is a private API?)

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • Create/design your view as landscape however, present it portrait. So when it appear it feels like the view is landscape, but for your app it is portrait. – Prajakta Apr 14 '18 at 23:46
  • You need the functionality of being able to select which view controllers allow which device orientations, which is certainly doable. This answer will help you: https://stackoverflow.com/questions/28938660/how-to-lock-orientation-of-one-view-controller-to-portrait-mode-only-in-swift – trndjc Apr 14 '18 at 23:56

0 Answers0