Rutger Huijsmans
Rutger Huijsmans

Reputation: 2408

Lock all screen orientations to portrait except for 1

I'm developing an iOS app that can only be accessed in portrait mode.

Except 1 framework (1 out of the 80 screens in my map) that I'm using needs Landscape support. Therefor I had to allow it in my plist.

What is the easiest way of making sure all other views are displayed in portrait and can only be displayed in portrait?

One good thing about my project is that all other ViewControllers inherit from ProjectViewController.

An answer in Swift is preferred.

Upvotes: 3

Views: 717

Answers (2)

André Slotta
André Slotta

Reputation: 14040

class ProjectViewController: UIViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

class RegularViewController: ProjectViewController {
    // do not neeed to override supportedInterfaceOrientations
}

class OneSpecificViewController: ProjectViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.portrait, .landscape]
    }
}

if your viewcontrollers are embedded in a navigationcontroller you can subclass it like this:

class CustomNavigationController: UINavigationController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        guard let topViewController = topViewController else {
            // default
            return .portrait
        }

        return topViewController.supportedInterfaceOrientations
    }
}

or even shorter...

class CustomNavigationController: UINavigationController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .portrait
    }
}

Upvotes: 4

hermannb
hermannb

Reputation: 58

Just edit AppDelegate

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

        let navController = UIApplication.sharedApplication().keyWindow?.rootViewController
        let topController = navController.viewControllers.last
        switch topController {
        case is ProjectViewController:
            return UIInterfaceOrientationMask.Portrait
        default:
            return UIInterfaceOrientationMask.All
        }

}

Upvotes: 1

Related Questions