Detecting orientation on loading

130 views Asked by At

When my simulator is in portrait and when my viewcontroller loads initially, it prints out Landscape instead of Portrait but when I change the orientaiton, it correctly displays the orientation so forth. I did the following

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()

  if (UIDevice.current.orientation == UIDeviceOrientation.portrait || UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown)
  {
    print("Portrait")
  }
  else
  {
    print("Landscape")
  }
}

I have no idea why it is displaying wrong orientation when it loads initially but once I rotate everything seems to work.

P.S. It seems like when simulator initially loads, the orientaiton is unknown, so it is choosing the else condition, how to avoid this from happening and identify the correct orientaiton?

2

There are 2 answers

6
pacification On BEST ANSWER
2
Nirav Hathi On
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
    print("landscape")
} else {
    print("portrait")
}