0

I want to know how to rotate a device even when a user turns on the portrait orientation lock in iPhone. Like the amazon prime video app, normally I see the app is in portrait mode, but when I start watching a movie, the app changes its rotation to horizontal even when I turn on the portrait orientation lock.

When I googled it, I only found this article, but using CoreMotion is the only way to achieve what I want to do??

I was using the following code to rotate the device from this article,

struct AppUtility {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {

        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {

        self.lockOrientation(orientation)

        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        UINavigationController.attemptRotationToDeviceOrientation()
    }

}

But the app doesn't rotate from portrait to landscape automatically (from landscape to portrait works...), but when I rotate the device from portrait to landscape by my hand, the app's view rotates.

So, how can I make the device rotation to landscape when I'm into a specific view controller? (like the prime video app automatically turns the orientation to landscape when I start watching movie)

Yuuu
  • 715
  • 1
  • 9
  • 32

1 Answers1

0

in AppDelegate following variable to lock all the controllers with given orientation

var orientationLock  = UIInterfaceOrientationMask.portrait

Now implement following method in AppDelegate

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

Write these methods in separate Helper file

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
    if let delegate = UIApplication.shared.delegate as? AppDelegate {
        delegate.orientationLock = orientation
    }
}

static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
    lockOrientation(orientation)
    UIDevice.current.setValue(rotateOrientation.rawValue, forKey: LocalizedKey.orientation.string)
}

Call this method in your specific controller's viewWillAppear()

    override func viewWillAppear(_ animated: Bool) {
    Helpers.lockOrientation(UIInterfaceOrientationMask.landscape,
                            andRotateTo: UIInterfaceOrientation.landscapeLeft)
}

NOTE: LocalizedKey.orientation.rawValue is string in separate file which have the value of "orientation"

Ghulam Mustafa
  • 196
  • 1
  • 7