Comment puis-je détecter l'orientation de l'appareil sur iOS?

j'ai une question sur la façon de détecter l'orientation du dispositif sur iOS. Je n'ai pas besoin de recevoir des notifications de changement, juste l'orientation actuelle elle-même. Cela semble être une question assez simple, mais je n'ai pas été en mesure d'enrouler ma tête autour de lui. Voici ce que j'ai fait jusqu'à présent:

UIDevice *myDevice = [UIDevice currentDevice] ;
[myDevice beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation deviceOrientation = myDevice.orientation;
BOOL isCurrentlyLandscapeView = UIDeviceOrientationIsLandscape(deviceOrientation);
[myDevice endGeneratingDeviceOrientationNotifications];

Dans mon esprit, cela devrait fonctionner. J'autorise l'appareil à recevoir des avis d'orientation de l'appareil, puis je demande dans quelle orientation il est, mais alors il ne fonctionne pas et je je ne sais pas pourquoi.

68
demandé sur Alexander Farber 2011-04-06 03:12:13

10 réponses

très vieux fil, mais pas de VRAIE solution.

j'ai eu le MÊME PROBLÈME, MAIS j'ai découvert que l'orientation UIDeviceOrientation n'est pas toujours cohérente, donc utilisez plutôt ceci:

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

if(orientation == 0) //Default orientation 
    //UI is in Default (Portrait) -- this is really a just a failsafe. 
else if(orientation == UIInterfaceOrientationPortrait)
    //Do something if the orientation is in Portrait
else if(orientation == UIInterfaceOrientationLandscapeLeft)
    // Do something if Left
else if(orientation == UIInterfaceOrientationLandscapeRight)
    //Do something if right
114
répondu Moe 2012-03-25 00:22:13

if UIViewController:

if (UIDeviceOrientationIsLandscape(self.interfaceOrientation))
{
    // 
}

si uivi:

if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
{
    //
}

UIDevice.h:

#define UIDeviceOrientationIsPortrait(orientation)  ((orientation) == UIDeviceOrientationPortrait || (orientation) == UIDeviceOrientationPortraitUpsideDown)
#define UIDeviceOrientationIsLandscape(orientation) ((orientation) == UIDeviceOrientationLandscapeLeft || (orientation) == UIDeviceOrientationLandscapeRight)

mise à Jour :

ajouter ce code au préfixe xxx.pch alors vous pouvez l'utiliser n'importe où:

// check device orientation
#define dDeviceOrientation [[UIDevice currentDevice] orientation]
#define isPortrait  UIDeviceOrientationIsPortrait(dDeviceOrientation)
#define isLandscape UIDeviceOrientationIsLandscape(dDeviceOrientation)
#define isFaceUp    dDeviceOrientation == UIDeviceOrientationFaceUp   ? YES : NO
#define isFaceDown  dDeviceOrientation == UIDeviceOrientationFaceDown ? YES : NO

utilisation:

if (isLandscape) { NSLog(@"Landscape"); }
76
répondu TONy.W 2013-02-15 19:12:00

si vous voulez obtenir l'orientation du dispositif directement de l'accéléromètre utiliser [[UIDevice currentDevice] orientation] . Mais si vous avez besoin de l'orientation actuelle de votre application( orientation interface ) utilisez [[UIApplication sharedApplication] statusBarOrientation] .

22
répondu rafalkitta 2015-01-07 22:56:15

pour ce que vous cherchez en premier vous devez obtenir Notification si L'Orientation a changé! Vous pouvez définir cette chose dans viewDidLoad comme

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

et chaque fois que L'Orientation de votre appareil a changé OrientationDidChange appelé où vous pouvez faire ce que vous voulez selon L'Orientation

-(void)OrientationDidChange:(NSNotification*)notification
{
    UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];

    if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight)
    {
    }
    else if(Orientation==UIDeviceOrientationPortrait)
    {
    }
}
21
répondu Saurabh Prajapati 2014-10-30 12:30:55

UIViewController possède une propriété interfaceOrientation à laquelle vous pouvez accéder pour connaître l'orientation actuelle d'un contrôleur de vue.

comme pour votre exemple, ça devrait marcher. Quand tu dis que ça ne marche pas, que veux-tu dire? Quels sont les résultats que vous obtenez par rapport à ce que vous attendiez?

9
répondu Jasarien 2011-04-05 23:15:25

Dans Swift 3.0

pour obtenir l'orientation du dispositif.

/* return current device orientation.
   This will return UIDeviceOrientationUnknown unless device orientation notifications are being generated. 
*/
UIDevice.current.orientation

pour obtenir l'orientation du dispositif de votre application

UIApplication.shared.statusBarOrientation
5
répondu Ashok R 2016-12-22 13:34:59

N'a pas été satisfait par " UIDeviceOrientation " parce que lorsqu'une orientation UIViewcontroller est fixée à une orientation spécifique, vous n'obtenez pas d'information pertinente avec l'orientation du périphérique, donc la bonne chose à faire est d'utiliser " UIInterfaceOrientation " .

vous pouvez obtenir l'orientation de L'UIViewController avec un " self.interfaceOrientation " , mais quand vous factorisez notre code, vous pourriez avoir besoin de faire ce genre de test en dehors d'un contrôleur de vue, (vue personnalisée, une catégorie...), de sorte que vous pouvez toujours accéder aux informations n'importe où en dehors du contrôleur en utilisant le rootviewController :

if (UIInterfaceOrientationIsLandscape(view.window.rootViewController.interfaceOrientation)) {
}
4
répondu Nicolas Lauquin 2013-07-12 08:06:44

avez-vous déverrouillé la serrure matérielle pour l'orientation de l'appareil? Il y en a un au bord de mon iPad 1.

1
répondu Martin Lütke 2011-04-05 23:24:31

il y a un moyen d'y parvenir, que la serrure d'orientation soit activée ou non en utilisant les données de CoreMotion. C'est le code:

#import <CoreMotion/CoreMotion.h> 

    CMMotionManager *cm=[[CMMotionManager alloc] init];
    cm.deviceMotionUpdateInterval=0.2f;
    [cm startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
                            withHandler:^(CMDeviceMotion *data, NSError *error) {

                            if(fabs(data.gravity.x)>fabs(data.gravity.y)){
                                    NSLog(@"LANSCAPE");
                                if(data.gravity.x>=0){
                                    NSLog(@"LEFT");
                                }
                                else{
                                    NSLog(@"RIGHT");
                                }

                        }
                        else{
                                NSLog(@"PORTRAIT");
                                if(data.gravity.y>=0){
                                    NSLog(@"DOWN");
                                }
                                else{

                                    NSLog(@"UP");
                                }

                            }

}];
1
répondu FlySoFast 2015-08-24 03:23:32

voici quelques variables Swift pour faciliter la détection:

let LANDSCAPE_RIGHT: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight
let LANDSCAPE_LEFT: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft
let LANDSCAPE: Bool = LANDSCAPE_LEFT || LANDSCAPE_RIGHT
let PORTRAIT_NORMAL: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait
let PORTRAIT_REVERSE: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown
let PORTRAIT: Bool = PORTRAIT_REVERSE || PORTRAIT_NORMAL
1
répondu Beninho85 2016-01-20 00:33:17