Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating the iPhone, and instantiating a new UIViewController?

Tags:

iphone

I would like to implement the following. When the user rotates the iPhone, I want to instantiate a new UIViewController (automatically upon rotation, not clicking a button or performing a similar action) and show to the user a view handled by this new UIViewController in landscape orientation. How to do this properly ?

I tried to instantiate the new controller in the methods willRotateToInterfaceOrientation and didRotateFromInterfaceOrientation, but none of this methods gets called!. I suspect this is because the current controller is pushed in by a navigation controller which is itself handled by a tabBarController. Any clue? A simple code snippet would be greatly appreciated.

Thank you in advance.

like image 222
Massimo Cafaro Avatar asked Apr 08 '09 16:04

Massimo Cafaro


1 Answers

A cleaner way is NOT to use UIInterfaceOrientation for the rotation.

Why, because then your interface or view 1 actually rotates. This means you have to rotate it back to redisplay it after view 2 is removed.

To compensate for this, I simple subscribe to UIDeviceOrientation notifications. Subtly different. View 1 does NOT have to support autorotation to make this method work. In viewDidLoad enter the following code:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectOrientation) name:@"UIDeviceOrientationDidChangeNotification" object:nil];

Then just define the method detectOrientation:

-(void) detectOrientation {

     if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
            ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {

        //load view 2


    } else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {

        // load view 1

    }   
}

Now neither of your views need support autoratation! You will however need to perform a transform on view 2 before loading:

-(void) transformView2ToLandscape {

  NSInteger rotationDirection;
  UIDeviceOrientation currentOrientation = [[UIDevice currentDevice] orientation];

  if(currentOrientation == UIDeviceOrientationLandscapeLeft){
    rotationDirection = 1;
  }else {
    rotationDirection = -1;
  }

  CGRect myFrame = CGRectMake(0, 0, 480, 300);
  CGAffineTransform transform = [[self view2] transform];
  transform = CGAffineTransformRotate(transform, degreesToRadians(rotationDirection * 90));
  [[self view2] setFrame: myFrame];
  CGPoint center = CGPointMake(myFrame.size.height/2.0, myFrame.size.width/2.0);
  [[self view2] setTransform: transform];
  [[self view2] setCenter: center];

}

Thats how I swap views o rotation without supporting autorotation in my views.

like image 142
Corey Floyd Avatar answered Nov 12 '22 16:11

Corey Floyd