EDITED: Frédéric Dal Bo wanted to be able to pass the current device's orientation into the getOrientation
method, as he couldn't call UIDevice.current
inside the extension he was using. Hopefully this will work, instead of detecting the UIDeviceOrientation
inside the getOrientation
method using UIDevice.current
, you can determine that from the Notification
, and then when you handle the notification, pass along the information:
func getOrientation(orientation: UIDeviceOrientation) {
switch orientation {
case .portrait:
print("Portrait")
case .landscapeLeft:
print("Lanscape Left")
case .landscapeRight:
print("Landscape Right")
case .portraitUpsideDown:
print("Portrait Upside Down")
case .faceUp:
print("Face up")
case .faceDown:
print("Face Down")
case .unknown:
print("Unknown")
}
}
When you initialize the class, or in viewDidLoad(_:)
if you're wanting to handle the change in a ViewController
:
NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
func deviceRotated(_ notification: Notification) {
let device = notification.object as! UIDevice
let orientation = device.orientation
getOrientation(orientation: orientation)
}
Then whenever the device rotates, the deviceRotated(orientation:)
will be called and it will pass the current device's orientation into the method. You can then handle the orientation change accordingly.