If your project is already in portrait you won’t need to change anything. If not, make sure that only portrait is selected.
![enter image description here](https://i.stack.imgur.com/fjHyo.png)
In Your AppDelegate add this:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
if let vcp = rootViewController as? ViewControllerRotateProtocol, vcp.canRotate() {
// Unlock landscape view orientations for this view controller
return [.landscapeLeft , .landscapeRight]
}
}
return application.supportedInterfaceOrientations(for: window)
}
private func topViewControllerWithRootViewController(rootViewController: UIViewController!) -> UIViewController? {
if (rootViewController == nil) { return nil }
if (rootViewController.isKind(of: UITabBarController.self)) {
return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UITabBarController).selectedViewController)
} else if (rootViewController.isKind(of: UINavigationController.self)) {
return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UINavigationController).visibleViewController)
} else if (rootViewController.presentedViewController != nil) {
return topViewControllerWithRootViewController(rootViewController: rootViewController.presentedViewController)
}
return rootViewController
}
Create one protocol: and you can expose this protocol to the app.
protocol ViewControllerRotateProtocol {
func canRotate() -> Bool
}
In Your View Controller, add this code:
class ViewController: UIViewController, ViewControllerRotateProtocol {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillDisappear(_ animated : Bool) {
super.viewWillDisappear(animated)
if (self.isMovingFromParentViewController) {
UIDevice.current.setValue(Int(UIInterfaceOrientation.portrait.rawValue), forKey: "orientation")
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return [.landscapeLeft , .landscapeRight]
}
func canRotate() -> Bool {
return true
} }