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

2

79

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?

Fordo answered 15/11, 2014 at 7:53 Comment(0)
E
196

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
    }
}
Evapotranspiration answered 15/11, 2014 at 8:35 Comment(2)
Is there a way to call something like this on a view itself, and not it's controller?Arnitaarno
@Arnitaarno A view should be rather "dumb," only recalculating its subview layout because something (either directly or indirectly) invoked setNeedsLayout. If you need to do something other than update layout on orientation change, feel free to keep a reference to a view and call whatever method you'd like to directly.Evapotranspiration
A
24

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");
    }  
}];
}
Abaca answered 21/2, 2017 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.