Question

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?

Was it helpful?

Solution

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
}

OTHER TIPS

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.

When the app loads, it does not know its current orientation-

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait) {
    NSLog(@"portrait");// only works after a rotation, not on loading app
}

Once you rotate the device, you get correct orientation, but when the app is loaded, without changing the orientation, it seems that using [[UIDevice currentDevice] orientation] doesn't know the current orientation.

So you need to do 2 things -

  1. Try setting the application's accepted device orientations in the plist file
  2. In your UIViewControllers, you will need to override the shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) method to return YES when the app should rotate:

If the is sequencing of relevant calls mean that you can't rely on interfaceOrientation having the correct value at viewWillAppear then — assuming the parent view controller rotates — the safest thing is probably self.parentViewController.interfaceOrientation. Failing that you could try making a first assumption from [[UIDevice currentDevice] orientation], which may not always be 100% on the money (e.g. if the device is lying flat on a table when your app is launched) but is likely to give you a better guess than always assuming portrait.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top