iOS. How to enable and disable rotation on each UIViewController?

Bao Tuan Diep picture Bao Tuan Diep · Aug 16, 2016 · Viewed 47.3k times · Source

I have an UIViewController, I want to disable or enable rotation of the screen in different scenarios

Example:

if flag {
   rotateDevice = false
}
else {
   rotateDevice = true
}

How can I do that?

Answer

Bao Tuan Diep picture Bao Tuan Diep · Aug 18, 2016

I have the answer. On AppDelegate, if you rotate device, push viewcontroller, etc. This function always call

Update for swift 3/4

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

self.restrictRotation is a custom parameter.

How to use:

In Appdelegate:

 var restrictRotation:UIInterfaceOrientationMask = .portrait

In ViewController:

When method ViewDidLoad or viewWillAppear is called. We will change like this:

(UIApplication.shared.delegate as! AppDelegate).restrictRotation = .all 

and then this method on AppDelegate will be called.

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask