It seems that when my app loads, it does not know its current orientation:
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (o
One thing that nobody has touched on yet is that you’re storing UIDeviceOrientation
types in a UIInterfaceOrientation
variable. They are different, and should not be treated as equal. Note that UIDeviceOrientationLeft
is equal to UIInterfaceOrientationRight
(since the interface rotates the opposite way compared to the device).
In order to obtain the orientation from the status bar it is also important to have the all the orientations enabled at the plist file.
Try the accelerometer to get its reading, UIAccelerometer, get sharedAccelerometer, set its delegate, get the readings, figure out from there orientation.
I still use this working code snippet for iphone 4:
-(void)deviceOrientationDidChange:(NSNotification *)notification{
//Obtaining the current device orientation
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
int value = 0;
if(orientation == UIDeviceOrientationPortrait)
{
value = 0;
}else if(orientation == UIDeviceOrientationLandscapeLeft)
{
value = 90;
}else if(orientation == UIDeviceOrientationLandscapeRight)
{
value = -90;
}
CGAffineTransform cgCTM = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(value));
[photoImageView setTransform:cgCTM];
}
for those who looking answer for Swift 3 or 4. just add that code inside of viewDidLoad() block.
let orientation = UIApplication.shared.statusBarOrientation
if orientation == .portrait {
// portrait
} else if orientation == .landscapeRight || orientation == .landscapeLeft{
// landscape
}
update for depreciation alerts for IOS 13 and Swift 5.x use code block below.
if #available(iOS 13.0, *) {
let orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
if orientation == .portrait {
// portrait
} else if orientation == .landscapeRight || orientation == .landscapeLeft{
// landscape
}
} else {
// Fallback on earlier versions
let orientation = UIApplication.shared.statusBarOrientation
if orientation == .portrait {
// portrait
} else if orientation == .landscapeRight || orientation == .landscapeLeft{
// landscape
}
}
the problem is that [UIDevice currentDevice]orientation]
sometimes reports the the device's orientation incorrectly.
instead use [[UIApplication sharedApplication]statusBarOrientation]
which is a UIInterfaceOrientation
so to check it you'll need to use the UIInterfaceOrientationIsLandscape(orientation)
hope this helps.