2011-01-21 58 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 2011-07-02 14:36:13