2009-05-30 10 views
12

Tengo el siguiente código en un método. Cuando ejecuto esto en el simulador, ¿el depurador se salta el código? ¿Qué me estoy perdiendo?UIDevice Orientation

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
     ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) 
{  

} else { 

} 
+0

¿Quiere decir que se salta sobre el caso y la persona, o que siempre va a la otra persona? –

+0

Sí, hay datos en if y else; y Sí se saltea todo el asunto. – Jordan

+0

Tal vez ayuda http://stackoverflow.com/q/634745/194544 – beryllium

Respuesta

18

Actualización 2

Esto no debería importar, pero intente encender las notificaciones de orientación:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 


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

actualización

Mi mal, asumí que estaba vacía.

Pruebe a eliminar la declaración o simplemente pruebe para una sola orientación. A ver si eso lo arregla. Tal vez hay un problema de soporte o algo tonto.

He la siguiente prueba que trabaja en el código de producción, por lo que su técnica debería funcionar:

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
     ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) { 


} 

respuesta original

Hay que poner realmente las declaraciones en el caso de los bloques para conseguir que se paso adentro.

El depurador es lo suficientemente inteligente como para omitir bloques vacíos.

+0

Sí, hay datos en el if y else; y Sí se saltea todo el asunto. – Jordan

+0

Gracias. Fue un problema tonto que perdí. Increíble. – Jordan

23

Tenga en cuenta que hay una macro UIDeviceOrientationIsLandscape y UIDeviceOrientationIsPortrait, por lo que en lugar de comparar por separado a LandscapeLeft y LandscapeRight sólo podría hacerlo de esta manera:

if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) 
{ 
} 
+0

problema en iOS 6 –

+0

¿qué problema? ... – inkredibl

53

La mejor manera de determinar la orientación de interfaz es mirar el estado orientación de la barra:

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 

    if(orientation == UIInterfaceOrientationPortrait || 
     orientation == UIInterfaceOrientationPortraitUpsideDown) { 

     //Portrait orientation 

} 

if(orientation == UIInterfaceOrientationLandscapeRight || 
    orientation == UIInterfaceOrientationLandscapeLeft) { 

    //Landscape orientation 

} 

medidas clase de orientación basado en acelerómetro y si el dispositivo está plano, no volverá la orientación correcta.

+7

uno debe aceptar esta respuesta .... – harshalb

+0

Gracias por esto. ¡¡¡Me salvó el día !! – virata

+0

'UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];' combinado con 'UIDeviceOrientationIsLandscape' y' UIDeviceOrientationIsPortait' es el camino a seguir. – Joe

0

Heh necesita llamar al [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications] antes de obtener el valor. Echa un vistazo a la documentación de este método. Me llevó un tiempo rastrear esto.

2

Otra forma de hacer esto sin necesidad de encender la orientación de notificación sería

Paso 1: Guardar la orientación actual en una variable local myCurrentOrientation y asignarla como esto:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
           duration:(NSTimeInterval)duration 
{ 
    myCurrentOrientation = toInterfaceOrientation; 
} 

Paso 2: Use myCurrentOrientation para su cheque

if (UIInterfaceOrientationIsLandscape(myCurrentOrientation) == YES) { 
    // landscape 
} 
else { 
    // portrait. 
} 
+0

Buen consejo. Pero tenga en cuenta que este código no se llama cuando el usuario cambia de orientación en otra vista y vuelve aquí. Solución agregando esto en un método conveniente: myCurrentOrientation = [[UIApplication sharedApplication] statusBarOrientation]; – FeltMarker

0

Digamos que está dentro de un pellizco Trampolín y quiere mostrar algo dependiendo de la orientación de la aplicación actual, entonces se puede utilizar este (sólo jailbreak):

UIInterfaceOrientation o = [[UIApplication sharedApplication] _frontMostAppOrientation]; 
0

recomiendo que utilice mi código en negrita en lugar de la suya para proteger un código de líneas.

-(void) viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self rotations]; 
} 

-(void)rotations 
{ 
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
    [[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(orientationChanged:) 
             name:UIDeviceOrientationDidChangeNotification 
             object:nil]; 
} 

-(void) orientationChanged:(NSNotification *)notification 
{ 
    //USE THIS PART 
    //USE THIS PART 
    //USE THIS PART 
    //USE THIS PART 
    //USE THIS PART 
    if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)) 
    { 
    } 
} 

EN LUGAR DE

if([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait || 
    [[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortraitUpsideDown) 
{ 
} 
0

Aquí es un método para encontrar la orientación y el verdadero centro de la pantalla. Usé el método de Tuszy para poder configurar UIActivityIndicatorView correctamente.

- (BOOL) isPortraitOrientation { 
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
    if(orientation == UIInterfaceOrientationPortrait || 
     orientation == UIInterfaceOrientationPortraitUpsideDown) { 
     return true; 
    } 
    if(orientation == UIInterfaceOrientationLandscapeRight || 
     orientation == UIInterfaceOrientationLandscapeLeft) { 
     return false; 
    } 
    return false; 
} 

Y la manera de conseguir el centro ...

- (void) findMyUIViewCenter { 
    CGPoint myCenter; 
    if ([self isPortraitOrientation]) { 
     myCenter = self.view.center; 
    } 
    else { 
     myCenter = CGPointMake(self.view.frame.size.height/2.0, self.view.frame.size.width/2.0); 
    } 
    NSLog(@"true center -- x:%f y:%f)",myCenter.x,myCenter.y); 
} 
Cuestiones relacionadas