skip to Main Content

I want to turn off the device rotation programmatically. I tried the below solution but this doesn’t work for me.

private func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
    if shouldRotate == true {
        return Int(UIInterfaceOrientationMask.portrait.rawValue)
    } else {
        return Int(UIInterfaceOrientationMask.landscapeLeft.rawValue)
    }
}

2

Answers


  1. I’m assuming your default rotation is .portrait. So in AppDelegate file, conform supportedInterfaceOrientationsFor then declare a property UIInterfaceOrientationMask, set it to .portrait.

    @main
    class AppDelegate: UIResponder, UIApplicationDelegate {
        ....
        var defaultRotation: UIInterfaceOrientationMask = .portrait
    
        func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
            return defaultRotation
        }
    }
    
    Login or Signup to reply.
  2. The supportedInterfaceOrientationsForWindow method you mentioned is outdated. Instead, you should use the supportedInterfaceOrientations method in your view controller to control the supported interface orientations.

    Should look like this:

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if shouldRotate {
            return .portrait
        } else {
            return .landscapeLeft
        }
    }
    

    Make sure you override the supportedInterfaceOrientations property in the view controller where you want to control the rotation behavior. This will allow you to specify whether the view controller supports portrait or landscape orientations based on your shouldRotate flag.

    Also, ensure that you have set the correct initial orientation settings for your app in your project settings. You can do this in Xcode by selecting your project, going to the "General" tab, and configuring the "Device Orientation" settings to match your desired behavior.

    I hope I could help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search