iOS: Device orientation on load

前端 未结 16 1832
遥遥无期
遥遥无期 2020-11-28 23:45

It seems that when my app loads, it does not know its current orientation:

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (o         


        
相关标签:
16条回答
  • 2020-11-29 00:25

    Swift 3 based on @Marjin 's code.

    var portraitOrientation = UIDevice.current.orientation == .portrait
    
    if UIDevice.current.orientation == .unknown || UIDevice.current.orientation == .faceUp {
         portraitOrientation = UIApplication.shared.statusBarOrientation == .portrait
    }
    
    if(portraitOrientation)
    {
         // Portrait
    }
    else
    {
    
    }
    
    0 讨论(0)
  • 2020-11-29 00:25

    Tried all and no good results. So what I did, as I'm on an ipad, was to leave all the work to the splitViewController methods to invalidate the barButton:

    For portrait:

    - (void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController: (UIPopoverController *)pc { NSlog(@"portrait");}
    

    For landscape:

    - (void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem{ NSlog(@"landscape");}
    

    this always works on load.

    0 讨论(0)
  • 2020-11-29 00:27

    I think this will work:

     [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];UIInterfaceOrientation orientation = [UIDevice currentDevice].orientation;
    

    According to the UIDevice reference:
    Quote:
    "The value of this property always returns 0 unless orientation notifications have been enabled by calling beginGeneratingDeviceOrientationNotifications"
    I had initially assumed that this property contained the current orientation at all times, but not so, apparently. I guess that turning on notifications is being handled for us behind the scenes in other situations where the orientation property is typically accessed, so it wasn't obvious that this needs to be done manually inside the app delegate

    0 讨论(0)
  • 2020-11-29 00:28

    Everyone above posted very valid answers : but as an UPDATE: Apple's take : you should e using UIStatusBar orientations to read current orientation of the device:

    One way you could check the current orientation of the device is by using an int values as such, inside the viewDidLoad method :

        int orientationType = [[UIDevice currentDevice] orientation];
    

    where consider the following . . . - 1 = portrait (right way up) - 2 = portrait upside down - 3 = landscape (right) - 4 = landscape (left)

    and then you could use an IF statement to call a method after orientation is detected, so on and so forth:

    Hope this was slightly helpful to someone

    0 讨论(0)
提交回复
热议问题