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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12681304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:50:56  来源:igfitidea点击:

iOS 6 - How to run custom code when orientation changes

iosxcodecocos2d-iphoneios6device-orientation

提问by James

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.

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

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:

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

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.

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

回答by Darren

Listen for device orientation changes:

监听设备方向变化:

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

When notified, get the device orientation from UIDevice:

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

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