Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITraitCollection iPad how to detect the current orientation

Since iOS8 methods to detect the orientation of a UIViewController are deprecated.
For instance -interfaceOrientation is deprecated, to detect the current view controller orientation it seems that we need to ask this information to the -traitCollection property on view controllers.
I'm bit confused iPad has his traits set to regular in both orientation.
What is the best approach to detect current orientation?

like image 318
Andrea Avatar asked Dec 04 '25 14:12

Andrea


2 Answers

Using -orientation property of UIDevice is not correct (even if it could work in most of cases) and could lead to some bugs, for instance UIDeviceOrientation consider also the orientation of the device if it is face up or down, there is no pair in UIInterfaceOrientation enum for those values.
Furthermore, if you lock your app in some particular orientation, UIDevice will give you the device orientation without taking that into account.
On the other side iOS8 has deprecated the interfaceOrientation property on UIViewController class.
There are 2 options available to detect the interface orientation:

  • Use the status bar orientation
  • Use size classes, on iPhone if they are not overridden they could give you a way to understand the current interface orientation

What is still missing is a way to understand the direction of a change of interface orientation, that is very important during animations.
In the session of WWDC 2014 "View controller advancement in iOS8" the speaker provides a solution to that problem too, using the method that replaces -will/DidRotateToInterfaceOrientation.

Here the proposed solution partially implemented:

-(void) viewWillTransitionToSize:(CGSize)s withTransitionCoordinator:(UIVCTC)t {
    orientation = [self orientationFromTransform: [t targetTransform]]; 
    oldOrientation = [[UIApplication sharedApplication] statusBarOrientation]; 
    [self myWillRotateToInterfaceOrientation:orientation duration: duration]; 
    [t animateAlongsideTransition:^(id <UIVCTCContext>) {
         [self myWillAnimateRotationToInterfaceOrientation:orientation
                                                  duration:duration];
      }
      completion: ^(id <UIVCTCContext>) {
         [self myDidAnimateFromInterfaceOrientation:oldOrientation];
      }];
}
like image 130
Andrea Avatar answered Dec 07 '25 05:12

Andrea


Look up the UIDeviceOrientation part of UIDevice and its orientation property. The docs are here. This is how I do my orientation checks. You can also see if the screen width is larger than the screen height since sometimes, especially on first launch of the app, it will be UIDeviceOrientationUnknown.

like image 45
Doug Watkins Avatar answered Dec 07 '25 05:12

Doug Watkins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!