Force landscape mode in one ViewController using Swift
It may be useful for others, I found a way to force the view to launch in landscape mode:
Put this in the viewDidLoad():
let value = UIInterfaceOrientation.landscapeLeft.rawValueUIDevice.current.setValue(value, forKey: "orientation")
and,
override var shouldAutorotate: Bool { return true}
Swift 4
override func viewDidLoad() { super.viewDidLoad() let value = UIInterfaceOrientation.landscapeLeft.rawValue UIDevice.current.setValue(value, forKey: "orientation")}override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscapeLeft}override var shouldAutorotate: Bool { return true}
If your view is embedded in a navigation controller, the above alone won't work. You have to cascade up by the following extension after the class definition.
extension UINavigationController {override open var shouldAutorotate: Bool { get { if let visibleVC = visibleViewController { return visibleVC.shouldAutorotate } return super.shouldAutorotate }}override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ get { if let visibleVC = visibleViewController { return visibleVC.preferredInterfaceOrientationForPresentation } return super.preferredInterfaceOrientationForPresentation }}override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{ get { if let visibleVC = visibleViewController { return visibleVC.supportedInterfaceOrientations } return super.supportedInterfaceOrientations }}}
Swift 3
override func viewDidLoad() { super.viewDidLoad() let value = UIInterfaceOrientation.landscapeLeft.rawValue UIDevice.current.setValue(value, forKey: "orientation")}private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.landscapeLeft}private func shouldAutorotate() -> Bool { return true}
Swift 4 , Tested in iOS 11
You can specify the orientation in projectTarget -> General -> DeploymentInfo(Device Orientation) -> Portrait (Landscapeleft and Landscaperight are optional)
AppDelegate
var myOrientation: UIInterfaceOrientationMask = .portrait func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return myOrientation }
LandScpaeViewController
override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.myOrientation = .landscape}
OnDismissButtonTap
let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.myOrientation = .portrait
Thats it. :)