UIDevice set orientation not working on iPad

1.5k views Asked by At

What I'm trying to achieve is that when user presses a button, to programmatically simulate device rotation to landscape. I've this code that is working for iPhone devices but not for iPads

let value = NSNumber(integerLiteral: UIDeviceOrientation.landscapeRight.rawValue)
UIDevice.current.setValue(value, forKey: "orientation")
ViewController.attemptRotationToDeviceOrientation()

Is there a way to achieve the same on iPads?

2

There are 2 answers

1
leandrodemarco On BEST ANSWER

Well the direct solution to this is pretty simple but it has a drawback. It is fixed by setting Requires Full Screen to true in the project settings General section. Of course, this means your app won't support multitasking, which may not be suitable depending on your app.

enter image description here

0
desmond_yy On

How do you detect changes in device orientation? If you use

func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)

to detect, then it won't be called on iPad. You can use this instead

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { (_) in
        let orient = UIApplication.shared.statusBarOrientation
        if orient.isPortrait {
            // portrait now
        } else if orient.isLandscape {
            // landscape now
        }
    }, completion: nil)
    super.viewWillTransition(to: size, with: coordinator)
}