Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
961 views
in Technique[技术] by (71.8m points)

xcode - 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.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Listen for device orientation changes:

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

When notified, get the device orientation from UIDevice:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...