View rotation notifications: why didRotateFromInterfaceOrientation: doesn't get called?

Francesco Puglisi picture Francesco Puglisi · May 24, 2011 · Viewed 24.9k times · Source

I'm trying to detect any device orientation change so that I can update the views.

I want to update the views whether the orientation is portrait or landscape, so I implemented this method:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

I know that if I want to update the views to show properly for the current orientation, I will need to implement some of the following methods:

– willRotateToInterfaceOrientation:duration:
– willAnimateRotationToInterfaceOrientation:duration:
– didRotateFromInterfaceOrientation:
– willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:
– didAnimateFirstHalfOfRotationToInterfaceOrientation:
– willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:

Now, the problem is that I don't understand why none of these methods get fired when I rotate the simulator.

I tried as well this piece of code:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

But still nothing. So I'm wondering, does the simulator fire rotation notifications? If yes, what am I doing wrong?

Answer

Alkimake picture Alkimake · May 24, 2011

You need to add notification observer something like

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

and add the method

- (void) didRotate:(NSNotification *)notification
{   
      UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

       if (orientation == UIDeviceOrientationLandscapeLeft)
      {
        NSLog(@"Landscape Left!");
      }
}