iOS 6 - 如何在方向更改时运行自定义代码

Jam*_*mes 12 xcode cocos2d-iphone device-orientation ios ios6

我正在创建一个允许设备处于横向左侧或横向右侧方向的游戏,玩家可以在暂停时更改方向.当他们这样做时,我需要改变游戏根据方向解释加速度计的方式.

在iOS 5中,我使用了willRotateToInterfaceOrientation来捕获更改并更改我的变量,但这在iOS6中已被弃用.我现有的代码如下所示:

    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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道替换是UIViewController类中的viewWillLayoutSubviews方法.我正在cocos2d 2.1中构建这个游戏,并且在演示项目中似乎没有UIViewController类,所以我不清楚如何合并它以及代码应该如何使其工作.

Dar*_*ren 36

监听设备方向更改:

[[NSNotificationCenter defaultCenter] 
       addObserver:self
          selector:@selector(deviceOrientationDidChangeNotification:) 
              name:UIDeviceOrientationDidChangeNotification 
            object:nil];
Run Code Online (Sandbox Code Playgroud)

收到通知后,从UIDevice获取设备方向:

- (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    switch (orientation)
    {
        // etc... 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @JamesMorrison设备方向和界面方向是两个不同的枚举和两个不同的概念.界面方向由软件控制(响应设备方向); 例如,您的软件方向将只是横向左侧或横向右侧.设备方向由硬件控制,可以随时进行任何操作,包括没有映射到界面方向的方向,如面朝上或面朝下.您只需要注意以下事实:您需要忽略许多设备方向更改. (4认同)
  • 给定任务的+1正确选项.要小心,因为你也会得到关于面向上和向下方向变化的通知,并注意"UIInterfaceOrientation ..."和"UIDeviceOrientation ......"之间的区别. (3认同)