Landscape orientation View Controller App Delegate

1.6k Views Asked by At

I'm trying to put only a View Controller in Landscape mode and the other ones in Portrait mode.

First of all, I've tried to invalidate the rotation of each View Controller except for the one I want (With shouldAutoRotate false, only Portrait, ...), but with a Navigation Controller I have, it overlaps the Nav bar with the Status Bar, and I couldn't solve it. So after that, I've tried to clean everything I've done and enable or disable the Orientation ONLY from the AppDelegate.

So here's a code I found and tried:

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

        if self.window?.rootViewController?.presentedViewController is SecondViewController {

            let secondController = self.window!.rootViewController!.presentedViewController as! SecondViewController

            if secondController.isPresented {
                return Int(UIInterfaceOrientationMask.All.rawValue);
            } else {
                return Int(UIInterfaceOrientationMask.Portrait.rawValue);
            }
        } else {
            return Int(UIInterfaceOrientationMask.Portrait.rawValue);
        }

    }

But this code never goes in the first if (even if the View controller is SecondViewController).

So any idea of how I can check if I'm in a specific VC that I can specify the orientation?

Thanks in advance!

1

There are 1 best solutions below

4
On BEST ANSWER

Checkout this recursive method for getting current viewController

func getCurrentViewController(viewController:UIViewController?)-> UIViewController?{

    if let tabBarController = viewController as? UITabBarController{

        return getCurrentViewController(tabBarController.selectedViewController)
    }

    if let navigationController = viewController as? UINavigationController{
        return getCurrentViewController(navigationController.visibleViewController)
    }

    if let viewController = viewController?.presentedViewController {

        return getCurrentViewController(viewController)

    }else{

        return viewController
    }
}

And use it on supported orientation method as follow

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

    if let currentVC = getCurrentViewController(self.window?.rootViewController) as? SecondViewController{

            return Int(UIInterfaceOrientationMask.All.rawValue)

    }
    return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}