cocos2d-iphonescreen-orientationcclayer

Disallow orientation in a certain CCLayer only


Globally my game supports two orientations: landscape right and landscape left

In one subscreen (inheriting CCLayer) I need to lock the current orientation so that ... the current orientation is locked... When the user pops back to another screen (CCLayer), orientation should work freely again.


Solution

  • I did it like this:

    Edit AppDelegate.h, add a mask for locking orientation:

    @interface MyNavigationController : UINavigationController <CCDirectorDelegate>
    @property UIInterfaceOrientationMask lockedToOrientation;
    @end
    

    In AppDelegate.m, synthesize the mask, and replace two functions:

    @synthesize lockedToOrientation; // assign
    
    -(NSUInteger)supportedInterfaceOrientations {
        if (!self.lockedToOrientation) {
            // iPhone only
            if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone )
                return UIInterfaceOrientationMaskLandscape;
    
            // iPad only
            return UIInterfaceOrientationMaskLandscape;
        }
        else {
            return self.lockedToOrientation;
        }
    }
    
    // Supported orientations. Customize it for your own needs
    // Only valid on iOS 4 / 5. NOT VALID for iOS 6.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        if (!self.lockedToOrientation) {
            // iPhone only
            if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone )
                return UIInterfaceOrientationIsLandscape(interfaceOrientation);
    
            // iPad only
            // iPhone only
            return UIInterfaceOrientationIsLandscape(interfaceOrientation);
        }
        else {
            // I don't need to change this at this point
            return NO;
        }
    }
    

    Then whenever I need to lock interface to a certain orientation, I access navController in the appdelegate. Check its interfaceOrientation property and set locked mask accordingly

    AppController* appdelegate = (AppController*)[UIApplication sharedApplication].delegate;
    const UIDeviceOrientation ORIENTATION = appdelegate.navController.interfaceOrientation;
    appdelegate.navController.lockedToOrientation = ORIENTATION == UIInterfaceOrientationLandscapeLeft ? UIInterfaceOrientationMaskLandscapeLeft : UIInterfaceOrientationMaskLandscapeRight;
    

    In dealloc or whenever I wanna remove the lock, I do this:

        AppController* appdelegate = (AppController*)[UIApplication sharedApplication].delegate;
        appdelegate.navController.lockedToOrientation = 0;