如何订阅设备方向事件(而不是界面方向)?

13

在我的应用程序中,我想在设备旋转(方向更改)的情况下调用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);
    }
}

但是在这种情况下,只有在启用自动旋转时才能收到通知。(如果它被禁用,设备实际上不会更改状态栏的方向)。你能帮我吗?

1个回答

29
[[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;

使用设备方向感应太过敏感,当处于45度横屏时会自动切换为竖屏。 - danfordham
这就是为什么它被称为设备方向而不是界面方向的原因。移动设备可以根据用户的持握方式非常频繁地更改其方向。对于界面方向感兴趣的人应该使用UIViewController的属性 :) - nacho4d

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接