How To Force Landscape Orientation in Swift

By Eddy Chung

Forcing landscape is a common task for iOS games or video.

How To Force Landscape Orientation In A View Controller In Swift

In your viewDidLoad add the following lines:

override func viewDidLoad() {
    super.viewDidLoad()
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}

You’ll also need to add supportedInterfaceOrientations:

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscapeLeft
}

And shouldAutorotate:

override var shouldAutorotate: Bool {
    return true
}

How To Force Landscape Orientation For Whole App In Swift

In your AppDelegate class define the property deviceOrientation:

var deviceOrientation = UIInterfaceOrientationMask.landscape

Then also add a supportedInterfaceOrientationsFor function in your AppDelegate:

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

Now your app should be in landscape. Note that you can choose .landscapeLeft or .landscapeRight.

If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts