Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I observe when a UIViewController changes interfaceOrientation?

If I have a pointer to a UIViewController, can I be notified when it changes interfaceOrientation without modifying the code of the controller?

Is my best bet to detect changes in device orientation and then see if the UIViewController will/has rotate(d)?

like image 652
Ben Flynn Avatar asked Jan 17 '13 20:01

Ben Flynn


2 Answers

You can use NSNotificationCenter :

 [[NSNotificationCenter defaultCenter] addObserver:self // put here the view controller which has to be notified
                                         selector:@selector(orientationChanged:)
                                             name:@"UIDeviceOrientationDidChangeNotification" 
                                           object:nil];
- (void)orientationChanged:(NSNotification *)notification{  
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

    //do stuff
    NSLog(@"Orientation changed");          
}
like image 123
Loris1634 Avatar answered Nov 08 '22 00:11

Loris1634


You can use the willAnimateRotationToInterfaceOrientation:duration: method on your UIViewController and then reposition any UIViews (or any other code) for landscape or portrait. E.g.

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
    // change positions etc of any UIViews for Landscape
  } else {
    // change position etc for Portait
  }

  // forward the rotation to any child view controllers if required
  [self.rootViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
}
like image 33
rogchap Avatar answered Nov 08 '22 02:11

rogchap