2012-03-19 26 views
8

Por favor, ayúdame. Tengo métodos:orientación actual del dispositivo iphone en ViewDidLoad

-(void) getCurrentOrientation{ 

    UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation]; 

    if(orientation == UIInterfaceOrientationPortrait){ 
     NSLog(@"portrait"); 
    } else if(orientation == UIInterfaceOrientationLandscapeRight) { 
     NSLog(@"LandscapeRight"); 
    } else if(orientation == UIInterfaceOrientationLandscapeLeft) { 
     NSLog(@"LandscapeLeft"); 
    } 
} 

pero cuando llamo a esto getCurrentOrientation tiro viewDidLoad

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self getCurrentOrientation]; 

} 

NSLog está vacía. ¿Qué pasa? también trato

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 

    if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait)) { 
     NSLog(@"portrait"); 

    } else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) 

    { 
     NSLog(@"LandscapeRight"); 
    } 

} 

sino que también varint vacía.

¡Tengo que saber en qué ORIENTACIÓN el usuario lanza la APLICACIÓN!

Por favor, dame algún consejo.

Respuesta

15

Su código es completamente correcto y no hay ningún problema.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 

Esta afirmación solo funciona en dispositivos originales.

Sin embargo desea comprobar en el simulador se puede comprobar como

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) { 
    // portrait    
} else { 
    // landscape 
} 

Actualización:

He probado para usted en tanto dispositivo y simulador. Inicialmente mostraría solo el retrato en viewDidLoad aunque mantendrá el dispositivo en el modo horizontal. El primer controlador analizará el método shouldAutoRotate.

No debe depender de en viewDidLoad para la orientación inicial. Primero debe confiar en el método shouldAutorotate para una orientación exacta.

+0

Gracias. Pero cuando corro en simulador en modo LANDSCAPE, NSlog da salida a PORTRAIT. Por lo tanto, no estoy seguro de que vaya a corregir el trabajo en el dispositivo real –

+0

Revise la respuesta actualizada –

+0

Selecciono en Proyecto - Objetivo - Resumen - Orientación del dispositivo compatible solo PAISAJE. Pero cuando ejecuto la aplicación en el sumulador con su función Nslog, retrato de salida. ¿Y por qué no debería depender? Solo necesito saber en qué orientación USER ejecuta la aplicación. –

2

Pruebe reemplazar su shouldAutorotateMethod por debajo shouldAutorotate

- (BOOL)shouldAutorotateToInterfaceOrientation (UIInterfaceOrientation)interfaceOrientation 
    { 
     if(interfaceOrientation == UIInterfaceOrientationPortrait){ 
      NSLog(@"portrait");  
     } else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight) {  
      NSLog(@"LandscapeRight");   
     } else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {  
      NSLog(@"LandscapeLeft"); 
     }   
     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown) 
    } 

Esto puede ayudarte.

+0

solo dígame, por favor, ¿por qué? No tengo ningún problema con shouldAutorotateToInterfaceOrientation. Tengo un problema con viewDidLoad. –

1

Si desea simplemente comprobar la orientación de aplicación a continuación, utilizar el código siguiente:

- (void) viewDidLoad { 
    [super viewDidLoad]; 
    BOOL isPortrait = UIDeviceOrientationIsPortrait(self.interfaceOrientation); 
    // now do whatever you need 
} 

o

-(void)viewDidLoad 
{ 
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) 
    { 
     //landscape view code 
    } 
    else 
    { 
     //portrait view code 
    } 
} 
1

Está su viewDidLoad llama? ¿Has puesto un punto de interrupción allí?

¿Qué tal simplemente impresión NSLog(@"%i", [[UIDevice currentDevice] orientation])?

La documentación dice que la orientación siempre devuelve 0, si no llamó al beginGeneratingDeviceOrientationNotifications. Quizás llamarlo justo antes de tratar de obtener la orientación no es suficiente. Intente mover la llamada al application:didFinishLaunchingWithOptions:.

Sin embargo, lo mejor es utilizar la orientación proporcionada por el controlador - [UIViewController interfaceOrientation] y el parámetro pasó a shouldAutorotateToInterfaceOrientation.

+0

Gracias por la respuesta. La orientación Sí siempre devuelve 0 y puse (como escribo arriba) beginGeneratingDeviceOrientationNotifications. Pero la orientación también devuelve 0. –

+0

Es por eso que digo que deberías tratar de moverlo a '[aplicación UIApplicationDelegate: didFinishLaunchingWithOptions:]' – Sulthan

+0

gracias, pero este método no es útil –

1

Cuando la aplicación se carga por primera vez, UIDevice.current.orientation no es válido. Pero UIApplication.shared.statusBarOrientation es. UIDevice.current.orientation es la mejor manera de verificar la orientación, en general, sin embargo. Por lo tanto, este método manejará todas las situaciones

func isLandscape() -> Bool { 
    return UIDevice.current.orientation.isValidInterfaceOrientation 
     ? UIDevice.current.orientation.isLandscape 
     : UIApplication.shared.statusBarOrientation.isLandscape 
} 
Cuestiones relacionadas