2011-01-21 3 views
12

В моем приложении я хочу вызвать некоторый метод в CCScene myscene в случае вращения устройства (изменение ориентации). Я отключил авторотацию (потому что я хочу, чтобы этого не произошло).Как подписаться на событие Ориентация устройства (не ориентация интерфейса)?

Проблема заключается в следующем: я хочу изменить гравитацию в сцене в зависимости от ориентации устройства. Мой код:

-(void) onEnter 
{ 
    [super onEnter]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification_OrientationWillChange:) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification_OrientationDidChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; 
} 
-(void) onExit 
{ 
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillChangeStatusBarOrientationNotification object:nil]; 
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; 
} 
-(void)notification_OrientationWillChange:(NSNotification*)n 
{ 
    orientation = (UIInterfaceOrientation)[[n.userInfo objectForKey:UIApplicationStatusBarOrientationUserInfoKey] intValue]; 
} 
-(void)notification_OrientationDidChange:(NSNotification*)n 
{ 
    if (orientation == UIInterfaceOrientationLandscapeLeft) { 
     b2Vec2 gravity(0, -10); 
     world->SetGravity(gravity); 
    } 
    if (orientation == UIInterfaceOrientationLandscapeRight) { 
     b2Vec2 gravity(0, 10); 
     world->SetGravity(gravity); 
    } 
} 

Но в этом случае я могу получать уведомления только в случае авторотации включен (если он отключен, устройство на самом деле не изменить его в строке состояния ориентации) Можете ли вы мне помочь.?

ответ

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



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

    //do stuff 
    NSLog(@"Orientation changed");   
} 

Вы должны проверить, не привязана ли настройка устройства к строке состояния.

typedef enum { 
     UIDeviceOrientationUnknown, 
     UIDeviceOrientationPortrait,   // Device oriented vertically, home button on the bottom 
     UIDeviceOrientationPortraitUpsideDown, // Device oriented vertically, home button on the top 
     UIDeviceOrientationLandscapeLeft,  // Device oriented horizontally, home button on the right 
     UIDeviceOrientationLandscapeRight,  // Device oriented horizontally, home button on the left 
     UIDeviceOrientationFaceUp,    // Device oriented flat, face up 
     UIDeviceOrientationFaceDown    // Device oriented flat, face down 
    } UIDeviceOrientation; 
+1

Добавлен недостающий '' ''. – Macarse

+0

Использование ориентации устройства слишком чувствительно, оно изменится на портрет при 45 градусах по горизонтали. – danfordham

+0

Вот почему это называется ** ориентация устройства **, а не ** ориентация интерфейса **. Мобильное устройство может очень сильно изменить свою ориентацию в соответствии с тем, как оно выполняется. Люди, заинтересованные в ориентации интерфейса, должны использовать свойство UIViewController :) – nacho4d

Смежные вопросы