2010-03-25 18 views
29

Tengo una aplicación con una barra de pestañas y controles de navegación en cada pestaña. Cuando el usuario sacude el dispositivo, aparece UIImageView como vista secundaria en el controlador de navegación. Pero el UIImageView debe contener una imagen especial, según la orientación actual del dispositivo.¿Cómo verificar en qué posición (horizontal o vertical) está el iPhone ahora?

Si escribo simplemente

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation) 
    if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) { 
    //Code 
    } 
    else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight||interfaceOrientation == UIInterfaceOrientationLandscapeLeft) { 
    //Code 
    } 
} 

La vista simplemente vuelve loco si el usuario gira el dispositivo antes de sacudir.

¿Hay algún método para obtener la orientación actual de los iPhones?

Respuesta

32

Utilice el método [[UIDevice currentDevice] orientation], como se especifica here.

+0

Gracias, pero que los valores pueden ser la orientación? Desde -90 hasta 90 - retrato y desde -180 hasta -90 y desde 90 hasta 180-paisaje? – Knodel

+0

Ver la respuesta de @ Shirkrin: devuelve un valor de tipo 'UIDeviceOrientation', que es un' enum' de una cierta lista de valores. – Tim

+1

no funcionó para mí, ya que a veces devuelve UIInterfaceOrientetionUnknown –

11

al complemento a la pregunta ya contestada:

Se utiliza [[UIDevice currentDevice] orientation] que producirá uno de estos valores:

typedef enum { 
    UIDeviceOrientationUnknown, 
    UIDeviceOrientationPortrait, 
    UIDeviceOrientationPortraitUpsideDown, 
    UIDeviceOrientationLandscapeLeft, 
    UIDeviceOrientationLandscapeRight, 
    UIDeviceOrientationFaceUp, 
    UIDeviceOrientationFaceDown 
} UIDeviceOrientation; 

La documentación se puede encontrar here - (orientation) y here - (UIDeviceOrientation).

(no me refiero a reclamar la antigua anwser, pero esta información era demasiado grande para sus comentarios.)

+0

Mucho más completo que mi respuesta. Gracias y +1 – Tim

6

También puede utilizar la propiedad interfaceOrientation de la clase UIViewController, si usted está atascado y conseguir continuamente UIDeviceOrientationUnknown desde UIDevice.

Hay un buen resumen de por qué [[UIDevice currentdevice] orientación] a veces puede fallar aquí: http://bynomial.com/blog/?p=25, especialmente si se desea detectar la orientación rápidamente (por ejemplo, si desea comprobar la derecha cuando la aplicación sale de la fondo).

+0

Creo que la publicación de blog es la mejor y la más completa para responder a esta pregunta. Gracias por enlazarlo. – andrrs

47

Éstos son macros UIDeviceOrientationIsLandscape y UIDeviceOrientationIsPortrait

así que en lugar de comprobar por separado puede hacerlo de esta manera ...

if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) 
{ 
    // code for landscape orientation  
} 

O

if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)) 
{ 
    // code for Portrait orientation  
} 
+3

He notado que estos no devuelven los valores correctos si la aplicación se inicia y aún no ha cambiado de orientación. ¿Hay alguna forma de evitar esto? –

17

Como dijo Beno, esto parece una mejor responde si estás detectando orientación desde el principio de tu Vista. No pude obtener la respuesta aprobada para devolver un resultado al principio de mi configuración, pero esto funciona maravillosamente.

if (UIDeviceOrientationIsPortrait(self.interfaceOrientation)){ 
//DO Portrait 
}else{ 
//DO Landscape 
} 
+0

¡Muchas gracias! – tmighty

+0

Gracias, esta es la respuesta que necesitaba. Para aclarar, el 'self' en su código es una instancia de UIViewController. – thijsai

+1

Esto puede no funcionar si el auto no es de pantalla completa. –

2

También puede definir constantes para ganar tiempo:

#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 
+0

#define LANDSCAPE UIDeviceOrientationIsLandscape ([UIDevice currentDevice] .orientation) Puede que desee volver a trabajar para los métodos en desuso. –

5

Le ayuda ...

-(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"); 
} 
} 
0

conseguir la orientación actual

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

// Do any additional setup after loading the view, typically from a nib. 

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 

    if (orientation == UIInterfaceOrientationLandscapeLeft) { 
     NSLog(@"Landscape left"); 
     self.lblInfo.text = @"Landscape left"; 
    } else if (orientation == UIInterfaceOrientationLandscapeRight) { 
     NSLog(@"Landscape right"); 
     self.lblInfo.text = @"Landscape right"; 
    } else if (orientation == UIInterfaceOrientationPortrait) { 
     NSLog(@"Portrait"); 
     self.lblInfo.text = @"Portrait"; 
    } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) { 
     NSLog(@"Upside down"); 
     self.lblInfo.text = @"Upside down"; 
    } 
} 
2

Prueba esto:

[[UIApplication sharedApplication] statusBarOrientation] 

O en Swift 3:

UIApplication.shared.statusBarOrientation 

Para comprobar específicamente para una orientación particular también puede prueba el isLandsc mono o bienes isPortrait como:

UIApplication.shared.statusBarOrientation.isLandscape 

El problema con [[UIDevice currentDevice] orientación] es que también volverá UIInterfaceOrientetionUnknown cuales statusBarOrientation no lo hace.

Existe también una propiedad UIViewController "interfaceOrientation" pero está desfasada y en iOS 8, así que no es recomendable.

devolver a la salida documentación para statusBarOrientation here

1

terminé comprobar como tal (Swift 3):

var isPortrait: Bool { 
    let orientation = UIDevice.current.orientation 
    switch orientation { 
    case .portrait, .portraitUpsideDown: 
     return true 

    case .faceUp: 
     // Check the interface orientation 
     let interfaceOrientation = UIApplication.shared.statusBarOrientation 
     switch interfaceOrientation{ 
     case .portrait, .portraitUpsideDown: 
      return true 
     default: 
      return false 
     } 
    default: 
    return false 
    } 
} 
Cuestiones relacionadas