I have an app with a tab bar, and nav controllers in each tab. When user shakes the device, a UIImageView
appears as a child view in the nav controller. But the
It helps you...
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft || [[UIDevice currentDevice] orientation ]== UIDeviceOrientationLandscapeRight)
{
NSLog(@"Lanscapse");
}
if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown )
{
NSLog(@"UIDeviceOrientationPortrait");
}
}
You can also define constants to earn time :
#define LANDSCAPE UIInterfaceOrientationIsLandscape(self.interfaceOrientation)
#define LANDSCAPE_RIGHT [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft
#define LANDSCAPE_LEFT [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight
#define PORTRAIT UIInterfaceOrientationIsPortrait(self.interfaceOrientation)
#define PORTRAIT_REVERSE [UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown
Updating this to iOS 8+ where the UIViewController.interfaceOrienation
is deprecated, you should use traitCollections
. So for example, to check for landscape on iPhone, you'd use:
if self.traitCollection.verticalSizeClass == .compact
{
your code
}
Notice that this is not the case on iPad, because on iPad in landscape, the size class is not compact
.
Apple Doc Link
You can also use the interfaceOrientation property of the UIViewController class, if you are stuck and continuously getting UIDeviceOrientationUnknown from UIDevice.
There's a good summary of why [[UIDevice currentdevice] orientation] can sometimes fail here: http://bynomial.com/blog/?p=25, especially if you want to detect the orientation quickly (for example, if you wanted to check right when the app comes out of the background).
Use the [[UIDevice currentDevice] orientation]
method, as specified here.
As Simple Solution of Swift 4.2
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
switch UIDevice.current.orientation{
case .portrait:
print("Portrait")
case .portraitUpsideDown:
print("PortraitUpsideDown")
case .landscapeLeft:
print("LandscapeLeft")
case .landscapeRight:
print("LandscapeRight")
default:
print("Another")
}
}