iOS 6 - 如何在方向更改时运行自定义代码 [英] iOS 6 - How to run custom code when orientation changes
问题描述
我创建的游戏允许设备处于横向左侧或横向右侧方向,并且播放器可以在暂停时更改方向。当他们做我需要改变游戏解释加速度计的方向根据方向。
I'm creating a game that allows the device to be in either landscape-left or landscape-right orientation, and the player can change the orientation while it's paused. When they do I need to change the way the game interprets the accelerometer based on the orientation.
在iOS 5中我使用了willRotateToInterfaceOrientation来捕获更改和更改我的变量,但在iOS6中已弃用。我现有的代码看起来像这样:
In iOS 5 I used the willRotateToInterfaceOrientation to catch changes and change my variables, but that's deprecated in iOS6. My existing code looks like this:
if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
rect = screenRect;
else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
rect.size = CGSizeMake( screenRect.size.height, screenRect.size.width );
GameEngine *engine = [GameEngine sharedEngine];
if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
engine.orientation = -1;
} else {
engine.orientation = 1;
}
}
我理解替换是viewWillLayoutSubviews方法UIViewController类。我在cocos2d 2.1中构建这个游戏,并且似乎在演示项目中没有UIViewController类,所以我不清楚如何合并它和代码应该看起来为了使这项工作。 / p>
I understand that the replacement is the viewWillLayoutSubviews method in the UIViewController class. I'm building this game in cocos2d 2.1 and there doesn't appear to be a UIViewController class in the demo project, so I'm not clear on how to incorporate it and how the code should look in order to make this work.
推荐答案
监听设备方向更改:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(deviceOrientationDidChangeNotification:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
通知时,从UIDevice获取设备方向:
When notified, get the device orientation from UIDevice:
- (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
switch (orientation)
{
// etc...
}
}
这篇关于iOS 6 - 如何在方向更改时运行自定义代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!