Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How do I figure out the current orientation in viewWillAppear?

I have a UIWebView that I would like to load different URLs depending on whether its portrait or landscape. How can I figure out what my current orientation is inside viewWillAppear?

like image 384
Gibson Avatar asked Oct 31 '11 17:10

Gibson


People also ask

How do I know if my device is landscape or portrait Swift?

orientation. isLandscape { print("Device is in landscape mode") } else { print("Device is in portrait mode") } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { determineMyDeviceOrientation() } override func didReceiveMemoryWarning() { super.

Which method called when orientation changes iOS?

Another way to detect device orientations is with the function traitCollectionDidChange(_:). The system calls this method when the iOS interface environment changes.


2 Answers

Use UIApplication's statusBarOrientation property. You may run into problems if you use the device orientation if it is UIDeviceOrientationFaceUp or UIDeviceOrientationFaceDown.

Example

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation))
{
   // Do something when in landscape
}
else
{
   // Do something when in portrait
}
like image 140
Sam Avatar answered Oct 05 '22 08:10

Sam


UIDeviceOrientation getCurrentOrientation() {
  UIDevice *device = [UIDevice currentDevice];
  [device beginGeneratingDeviceOrientationNotifications];
  UIDeviceOrientation currentOrientation = device.orientation;
  [device endGeneratingDeviceOrientationNotifications];

  return currentOrientation;
}

It's up to you to convert the UIDeviceOrientation to UIInterfaceOrientation.

like image 32
Marcelo Alves Avatar answered Oct 05 '22 08:10

Marcelo Alves