Search code examples
iosswiftxcodeuideviceorientation

Detecting orientation on loading


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?


Solution

  • You can check current orientation by UIApplication.shared.statusBarOrientation.isPortrait or UIApplication.shared.statusBarOrientation.isLandscape.