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?
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.
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.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With