iOS: How to run a function after Device has Rotated (Swift)
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");
}
}];
}