How to rotate orientation programmatically in Swift? How to rotate orientation programmatically in Swift? swift swift

How to rotate orientation programmatically in Swift?


To change orientation programatically in swift 3, use the following way:

let value = UIInterfaceOrientation.landscapeRight.rawValueUIDevice.current.setValue(value, forKey: "orientation")

You can use the orientations,

1. portrait2. portraitUpsideDown3. landscapeLeft4. landscapeRight


Swift 4:

enter image description here

Step1:

In Appdelegate - Declare deviceOrientation var which is portrait by default

import UIKitlet appDelegate = UIApplication.shared.delegate as! AppDelegate@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {    var window: UIWindow?    var deviceOrientation = UIInterfaceOrientationMask.portrait    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {        return deviceOrientation    }}

Step 2:

In your certain ViewController write this to change orientation -

 override func viewWillAppear(_ animated: Bool) {     appDelegate.deviceOrientation = .landscapeLeft     let value = UIInterfaceOrientation.landscapeLeft.rawValue     UIDevice.current.setValue(value, forKey: "orientation") } 


You can override UIViewController.supportedInterfaceOrientations() instead of triggering rotation in viewWillAppear

For Xcode 7

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {    return UIInterfaceOrientationMask.Landscape}

For Xcode 6

override func supportedInterfaceOrientations() -> Int {    return Int(UIInterfaceOrientationMask.Landscape.rawValue)}

And make sure the desired orientations are enabled in project settings.

enter image description here