Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to run a function after Device has Rotated (Swift)

I have one UIView which is not using Auto-Layout and some components are displayed based on their percent of X and Y co-ordinates from the main view.

Previously I would have run a function to update their positions in didRotateFromInterfaceOrientation however I see this is now deprecated in iOS8.

I've taken a look at viewWillTransitionToSize but it's giving weird results, and there doesn't appear to be a viewDidtransitionToSize function.

Is there an easy way (in Swift) to run a function after a device rotation?

like image 785
Richard Avatar asked Nov 15 '14 07:11

Richard


2 Answers

The viewWillTransitionToSize delegate method gets called with a UIViewControllerTransitionCoordinator conforming object. A method that protocol declares is animateAlongsideTransition(_:animation, completion:). You can use that to have code execute after the transition is complete.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: nil) { _ in
        // Your code here
    }
}
like image 121
Acey Avatar answered Nov 08 '22 00:11

Acey


Although not asked for here Objective C version:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {

    // change any properties on your views

} completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    if( UIDeviceOrientationIsPortrait(orientation) ) {
        NSLog(@"portrait");
    } else {
        NSLog(@"landscape");
    }  
}];
}
like image 24
Olivier de Jonge Avatar answered Nov 08 '22 01:11

Olivier de Jonge