How To Force Landscape Orientation in Swift

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 and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts