Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

swift2

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?

like image 663
Bao Tuan Diep Avatar asked Aug 16 '16 07:08

Bao Tuan Diep


People also ask

How do I keep Safari from rotating?

Tap the "Screen Rotation Lock" button, which resembles a circular arrow, at the far left of the bar. A padlock appears along with the words "Portrait Orientation Locked." To disable the screen orientation lock, tap the "Screen Rotation Lock" button again.

How do I turn auto rotate off in settings?

Short guide: Tap the Settings icon to open the Settings app. Scroll down and tap Accessibility. Scroll down to Interaction controls and tap Auto-rotate screen to turn it off.


2 Answers

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 
like image 61
Bao Tuan Diep Avatar answered Sep 21 '22 01:09

Bao Tuan Diep


You simply have to implement shouldAutorotate and supportedInterfaceOrientations into your UIViewController. Take a look at this documentation. For example:

override func shouldAutorotate() -> Bool {     return true } 

You can also specify which orientations are available. Here is an example with only portraits orientations:

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

Edit: If you want to support different orientation regarding a flag, you just have to do something like this:

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {     if myFlag {         return .Landscape     } else {         return .All     } } 

(If myFlag is true, it will allow Landscape orientation. Otherwise, it will allow all orientations).

like image 24
Julien Quere Avatar answered Sep 22 '22 01:09

Julien Quere