user7711128
user7711128

Reputation: 41

How to rotate to landscape only one view controller

I have used the following approach to make it feasible, but didn't work

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
}    

Upvotes: 0

Views: 119

Answers (2)

Infusion Analysts
Infusion Analysts

Reputation: 489

If you want to force Particular viewController rotate to landscape only then add the following code in AppDelega file

public var orientationLock = UIInterfaceOrientationMask.all

    static var shared : AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }


    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientationLock
    }

    func lockDeviceOrientation(orientationLock: UIInterfaceOrientationMask, rotateOrientation:UIInterfaceOrientation) {
        AppDelegate.shared.orientationLock = orientationLock
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }

And add the following code in particular viewController which you want to force to rotate in landscape only

 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        AppDelegate.shared.orientationLock = .landscapeLeft
    }

Upvotes: 1

B K.
B K.

Reputation: 534

In your AppDelegate.swift :

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if let navigationController = self.window?.rootViewController as? UINavigationController {
        if navigationController.visibleViewController is YourViewController {
            return UIInterfaceOrientationMask.all
        } else {
            return UIInterfaceOrientationMask.portrait
        }
    }
    return UIInterfaceOrientationMask.portrait
}

Upvotes: 0

Related Questions