2012-04-26 9 views
5

Necesito obtener la orientación del dispositivo desde un ViewController. I no pueden basar en:¿Cómo obtener la orientación del dispositivo a través de la referencia UIView?

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; 

porque a veces devuelve orientación desconocida (por ejemplo cuando el dispositivo se establecen en la tabla).

Sólo necesito saber en qué orientación se muestra mi UIView actual (¿es paisaje izquierdo u horizontal derecho?). No necesito que se actualice este valor cuando cambie la orientación, solo quiero saberlo cuando lo solicite. Sólo algunos referencia view.orientation;). ¿Hay algo que me pueda ayudar? He leído la documentación de UIView, he encontrado alguna referencia a UIWindow, pero nada que pueda ayudarme.

Respuesta

13

También puede obtener la orientación del dispositivo de UIApplication, ¿Ha intentado utilizar

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
+1

Eso es exactamente lo que yo era lo esperando por. Ahora puedo obtener la orientación de los componentes UIKit y usarla. ¡Muchas gracias! – thelion

-1

siguiente es el código de ejemplo para hacer lo mismo. Hay una variable llamada deviceOrientation, que responderá a la orientación actual del dispositivo, siempre que se le solicite.

UIDeviceOrientation deviceOrientation; 

- (void)viewWillAppear:(BOOL)animated 
{ 
    deviceOrientation = (UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation]; 
    [self willAnimateRotationToInterfaceOrientation:deviceOrientation duration:0.5]; 
} 

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration 
{ 
    deviceOrientation = (UIDeviceOrientation)interfaceOrientation; 
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) 
    { 
     NSLog(@"Landscape"); 
    } 
    else 
    { 
     NSLog(@"Portrait"); 
    } 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return TRUE; 
} 
4

UIViewController tiene una propiedad

UIInterfaceOrientation interfaceOrientation; 

Así que en su UIViewController, puede acceder a la orientación actual del dispositivo en cualquier momento a través de

UIInterfaceOrientation myCurrentOrientation = self.interfaceOrientation; 
+0

Desaprobado desde iOS 8.0 –

0

Swift Versión

let currentOrientation:UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation 


    if currentOrientation.isPortrait { 

     print("PORTRAIT") 

    } else if currentOrientation.isLandscape { 

     print("LANDSCAPE") 

    } 
Cuestiones relacionadas