Force landscape mode in one ViewController using Swift

sazz picture sazz · Nov 20, 2014 · Viewed 83.5k times · Source

I am trying to force only one view in my application on landscape mode, I am calling

override func shouldAutorotate() -> Bool {
    print("shouldAutorotate")
    return false
}

override func supportedInterfaceOrientations() -> Int {
    print("supportedInterfaceOrientations")
    return Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue)
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    return UIInterfaceOrientation.LandscapeLeft
}

The view is launched in the portrait mode, and keep rotating when I change the device orientation.
The shouldAutorotate is never called.
Any help would be appreciated.

Answer

sazz picture sazz · Nov 21, 2014

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.rawValue
UIDevice.current.setValue(value, forKey: "orientation")

and,

override var shouldAutorotate: Bool {
    return true
}