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?

32254 次浏览

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

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