在我的应用程序中我想在设备旋转(方向更改)的情况下调用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);
}
}
但在这种情况下,我只能在启用自动旋转的情况下收到通知。(如果禁用,设备实际上不会更改状态栏方向) 你能救我吗?
答案 0 :(得分: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;