How to force and rotate the orientation of only one ViewController in iOS using Swift 3

Wrote by: hoangnguyen     Create date: 19/07/2017     11910 views

An application has a lot of screens (or ViewController-s). If your the app's orientation will be forced to portrait/landscape by default. But, on a special screen, the app should support another orientation.

So, how to do it? In this tutorial, I will show you.

My application's orientation is forced to portrait mode. But, when the app navigates to the second screen, the second screen will change the orientation to landscape mode.

Deployment Info – Device Orientation

If your project is already in portrait you won’t need to change anything. If not, make sure that only portrait is selected.



class AppDelegate: UIResponder, UIApplicationDelegate {

    var orientationLock = UIInterfaceOrientationMask.portrait
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientationLock
    struct AppUtility {
        static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
            if let delegate = UIApplication.shared.delegate as? AppDelegate {
                delegate.orientationLock = orientation
        static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
            UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")


Create an AppUtility struct with 2 utilize method can lock and rotate the device orientation. Then, just use them in any ViewController you want to force the orientation. 




class ViewController: UIViewController {

    override func viewDidLoad() {
    override func viewWillAppear(_ animated: Bool) {
        AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.landscapeRight, andRotateTo: UIInterfaceOrientation.landscapeRight)

    override func viewWillDisappear(_ animated : Bool) {
        AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)


In the ViewController that you want to force the orientation, in viewWillAppear() method, invoke lockOrientation() method of AppUtility struct with the expected orientation.

And before the forced orientation ViewController disappears, make sure that it returns the default orientation of the app, call the AppUtility.lockOrientation() again with default orientation.

That's it. You can get the source code and run to see the result. Good luck :) 

Download source code Here

Nguyễn Ngọc Hoàng - Software Engineer
Ngoc Hoang Nguyen

If we cannot do anything, due to we haven't yet acquainted with it.

Go on will also reach to destination.

Follow me

Please wait