Khallad
Khallad

Reputation: 121

Allow only 1 view controller to be in landscape or portrait

my app is portrait what i wanna do is allow 1 view controller to be portrait or landscape i tried using this code in AppDelegate but i am getting an error

   func application(_ application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow) -> Int {

        let currentViewController: UIViewController? = self.topView


    // Get topmost/visible view controller
    var currentViewController: UIViewController? = self.topViewController
    // Check whether it implements a dummy methods called canRotate
    if currentViewController?.responds(to: #selector(self.canRotate)) {
    // Unlock landscape view orientations for this view controller
    return .allButUpsideDown
    }
    // Only allow portrait (standard behaviour)
    return .portrait
    }
}

Does anyone know how to do that in swift?

Upvotes: 2

Views: 1424

Answers (1)

CodeBender
CodeBender

Reputation: 36670

I took the following approach in my app.

Create a custom UINavigationController with the following code & make sure that your root navigation controller is updated to use this as its class.

import UIKit

class NavigationController: UINavigationController {
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
        if let _ = presentedViewController as? MyPortraitViewController {
            return .portrait
        }

        return .allButUpsideDown
    }
}

You can replace MyPortraitViewController with the class name of the view controller you wish to deviate from the global setting.

While I use .portrait in this example, you are free to use other options.

One implementation example would be to replace the class of your base navigation controller in your storyboard which is shown below.

enter image description here

Upvotes: 4

Related Questions