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

我正在创建一个游戏,允许设备在左侧或横向的方向,而播放器可以在暂停时改变方向.当我们需要改变游戏根据方向解释加速度计的方式时.

在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类,所以我不清楚如何并入它,以及代码应该如何使其工作.

解决方法

聆听设备方向更改:
[[NSNotificationCenter defaultCenter] 
       addObserver:self
          selector:@selector(deviceOrientationDidChangeNotification:) 
              name:UIDeviceOrientationDidChangeNotification 
            object:nil];

通知时,从UIDevice获取设备方向:

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...