iosswiftuiviewcontrollerlandscape

Force landscape mode in one ViewController using Swift


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() method is never called.

Any help would be appreciated.


Solution

  • 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
    }