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

12

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

在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;
    }
}

我知道替代方法是UIViewController类中的viewWillLayoutSubviews方法。 我正在使用cocos2d 2.1构建此游戏,并且演示项目中似乎没有UIViewController类,因此我不清楚如何将其合并以及代码应该看起来如何才能使其工作。

1个回答

36

监听设备方向变化:

[[NSNotificationCenter defaultCenter] 
       addObserver:self
          selector:@selector(deviceOrientationDidChangeNotification:) 
              name:UIDeviceOrientationDidChangeNotification 
            object:nil];

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

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

3
给定任务中的正确选项是+1。请注意,您还将收到有关面朝上和面朝下方向更改的通知,并注意UIInterfaceOrientationUIDeviceOrientation之间的区别。 - Till
@Till - 你所说的面朝上和面朝下是指它以纵向或倒置的方式定位吗?还是其他什么情况?此外,我认为DeviceOrientation和InterfaceOrientation几乎总是相同的,除非在特殊情况下,例如多个视图,或者如果已经通过编程设置InterfaceOrientation不匹配设备方向。还有其他需要注意的可能会导致问题的情况吗? - James
4
@JamesMorrison 设备方向和界面方向是两个不同的枚举和概念。界面方向由软件控制(根据设备方向),例如,您的软件方向只能是左横屏或右横屏。设备方向由硬件控制,可以随时任意更改,包括那些没有映射到界面方向的方向,例如正面朝上或者朝下。您只需要注意到有许多设备方向变化需要忽略即可。 - Darren

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