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

IosSwiftRotation

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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
    }
}

Solution 2 - Ios

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");
    }  
}];
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichardView Question on Stackoverflow
Solution 1 - IosAceyView Answer on Stackoverflow
Solution 2 - IosOlivier de JongeView Answer on Stackoverflow