12

I'm trying to find a method call I can latch onto once a device's orientation has changed. Is there something identical to didRotateFromInterfaceOrientation that isn't deprecated?

Brandon
  • 2,886
  • 3
  • 29
  • 44

3 Answers3

28

As of iOS 8, all UIViewControllers inherit the UIContentContainer protocol, one of whose methods is - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator, which you can (simplistically) override like this:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {

        // Stuff you used to do in willRotateToInterfaceOrientation would go here.
        // If you don't need anything special, you can set this block to nil.

    } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {

        // Stuff you used to do in didRotateFromInterfaceOrientation would go here.
        // If not needed, set to nil.

    }];
}

You'll notice there's nothing specific about orientation, which is by design; iOS view rotations are essentially a composition of a specific translation matrix operation (resizing a view from one aspect ratio to another is just a specific case of a general resizing operation where the source and target view sizes are known in advance) and a rotation matrix operation (which is handled by the OS).

fullofsquirrels
  • 1,828
  • 11
  • 16
3

Swift 3 version of fullofsquirrels's answer:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { context in
            context.viewController(forKey: UITransitionContextViewControllerKey.from)
            // Stuff you used to do in willRotateToInterfaceOrientation would go here.
            // If you don't need anything special, you can set this block to nil. 
        }, completion: { context in
            // Stuff you used to do in didRotateFromInterfaceOrientation would go here.
            // If not needed, set to nil.
        })
}
Mohit Singh
  • 1,452
  • 1
  • 18
  • 27
2

You could always register for the UIDeviceOrientationDidChangeNotification

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

- (void) didRotate:(id)sender
{
    UIInterfaceOrientation io = [[UIApplication sharedApplication] statusBarOrientation];


    ...
Mike M
  • 4,358
  • 1
  • 28
  • 48
  • Thanks for the answer, Mike. This works as well, but I prefer adhering to protocols over using notifications. – Brandon Aug 07 '15 at 01:46