Search code examples
iosiphoneswiftios9

Enable and disable auto rotate programmatically using Swift?


I would like to programmatically disable or enable the auto rotate function using a button using Swift. I was thinking that it might be able to somehow be done using the supportedInterfaceOrientations() function, but I am very confused after looking through the literature about how this is done. Is there an easy solution for this?


Solution

  • You could create an action for the button that sets a boolean flag somewhere in your code and return the value of that flag in the shouldAutorotate method of the view controller. If you need that for all view controllers you could create a common base view controller (inheritance).

    Example of button action:

    @IBAction func toggleRotation(sender: Button) {
        // A made up AppConfig class with class method for setting and retrieving 
        // rotation flag.
        AppConfig.allowRotation(!AppConfig.allowRotation)
    }
    

    Example of shouldAutorotate:

    override func shouldAutorotate() -> Bool {
        return AppConfig.allowRotation()
    }
    

    https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/shouldAutorotate