1

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?

leandrodemarco
  • 1,552
  • 1
  • 15
  • 22
  • You are right. You have my blessing. – El Tomato Apr 03 '19 at 02:47
  • https://stackoverflow.com/questions/32345409/how-to-rotate-orientation-programmatically-in-swift – zaitsman Apr 03 '19 at 02:57
  • @zaitsman That topic won't help in changing the orientation when you have an iPad. – El Tomato Apr 03 '19 at 03:44
  • @ElTomato how do you mean? you really can't change the orientation of the OS. but you can restrict which orientations your app recognises, and you can do so based on absolutely anything (programmatically), like day of the week or time of day, or userInterfaceIdiom – zaitsman Apr 03 '19 at 03:46
  • @zaitsman What is "the orientation of the OS"? I am saying that you can change the orientation with `UIDevice.current.setValue(value, forKey: "orientation")` if you have an iPhone. But the same scheme does not work if you do it with an iPad. – El Tomato Apr 03 '19 at 05:13
  • @zaitsman the question you post actually has pretty much this code as the most accepted answer (I probably took it from there). But as El Tomato says my problem is that it does not work on iPads. And I can’t find a reference to that particular issue in that question. Thought there could be some workaround to make it work but it seems not :( – leandrodemarco Apr 03 '19 at 05:35

2 Answers2

3

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

leandrodemarco
  • 1,552
  • 1
  • 15
  • 22
-1

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)
}
desmond_yy
  • 83
  • 6