VDog VDog - 9 months ago 44
Swift Question

In an extension, how to identify device orientation on iOS 10. It is not properly responding, or I am doing it wrong?

I've tried multiple methods to add an observer, and call this function:

In viewDidLoad

UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)


and also;

deinit {
NotificationCenter.default.removeObserver(self)
}

func deviceOrientationDidChange() {
print(UIDevice.current.orientation.rawValue)
// all return false
print(UIDevice.current.orientation.isFlat)
print(UIDevice.current.orientation.isPortrait)
print(UIDevice.current.orientation.isLandscape)
print(UIDevice.current.orientation.isValidInterfaceOrientation)

}


I've also tried:

UIDevice.current.orientation.isLandscape


and all the other possibilities like
.isLandscape
,
.IsFlat
, etc and none of them seem to be working either.

Answer Source

This is how I ended up getting the information:

func deviceOrientation() {
    if UIScreen.main.bounds.size.width < UIScreen.main.bounds.size.height {
        print("portrait")
    } else {
        print("landscape")
    }
}