0

I'm doing an app for Mathematics lessons & exercices...

I have only coded the MainMenu, but I've got a problem. Indeed, I would like to know the current orientation to set up my stuff.

However, I tried different ways to know the current orientation, but I didn't succeed :

if UIDevice.current.orientation == UIDeviceOrientation.portrait {
            NSLog("Portrait")

        }

        else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight || UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
            NSLog ("Landscape")
        }

I also see this answer, but it's not working (or maybe I haven't understood well) : Getting device orientation in Swift , bu

I would like to specify that I'm in UIViewController in the ViewDidLoad().

Thanks for your help ‍

Lucas A.
  • 1
  • 1

1 Answers1

0

I set up a little prototype app with a button which checks for device orientation changes when pressed. Here is a link to the documentation which hopefully helps further your project along.

class ViewController: UIViewController {

    let device = UIDevice.current

    override func viewDidLoad() {
        super.viewDidLoad()
        device.beginGeneratingDeviceOrientationNotifications()
    }

    @IBAction func orientation(_ sender: UIButton) {
        if device.isGeneratingDeviceOrientationNotifications {
            switch device.orientation {
            case .landscapeLeft:
                print("Landscape Left")
            case .portrait:
                print("Portrait")
            case .landscapeRight:
                print("Right")
            case .portraitUpsideDown:
                print("Upside down")
            case .unknown:
                print("Unknown")
            default:
                print("Else")
            }
        }
    }
}
Dan O'Leary
  • 916
  • 9
  • 20
  • This is overkill. The reason he isn't getting orientation is (actually he is getting UIDeviceOrientation.unknown) he is trying in viewDidLoad. – Desdenova Aug 23 '19 at 12:00
  • Agreed, but they did not appear to know the code so I wrote it out. Your comment above is also a much better way of getting notifications without requiring any user input. – Dan O'Leary Aug 23 '19 at 12:02