If keeping the animation is needed, an another option is to wrap in UIView.animation
which provides an animation completion callback. That callback will be called regardless of rotation and will actually indicate if the setViewControllers animation was cancelled due to a rotation.
Here's an extension method that encapsulates the solution:
extension UIPageViewController {
/// A drop-in replacement of `setViewControllers`. It fixes `viewControllers` not displaying properly
/// if the change animation was cancelled by iOS, which happens everytime the device is rotated.
///
/// See `UIPageViewController.setViewControllers` for parameter details.
///
/// More Info: https://stackoverflow.com/q/19268005/2191796
@objc
func setViewControllersPatched(_ viewControllers: [UIViewController]?, direction: UIPageViewController.NavigationDirection, animated: Bool, completion: ((Bool) -> Void)?) {
if animated {
// Track if completion gets called - since it's not guaranteed
// See: https://stackoverflow.com/q/19268005/2191796
var wasCompletionCalled = false
// Wrap in an animation block with it's own completion block that is guaranteed and will indicate if the inner animation gets cancelled
// The duration needs to be longer than the `setViewControllers` animation, otherwise `animationWasCancelled` will always be true.
UIView.animate(withDuration: 0.4) {
self.setViewControllers(viewControllers, direction: direction, animated: animated) { animationSkippedByUser in
wasCompletionCalled = true
completion?(animationSkippedByUser)
}
} completion: { animationWasCancelled in
// When `setViewControllers` is called and a rotation occurs, `animationWasCancelled` will be true - since iOS cancelled the animation.
if animationWasCancelled && !wasCompletionCalled {
print("UIPageViewController.setViewControllersPatched: Issue detected with canceled animation, fixing by setting view controllers without animation.")
self.setViewControllers(viewControllers, direction: .forward, animated: false, completion: completion)
}
}
} else {
// There is no layout/rotation issue when there is no animation - So just pass on the parameters
setViewControllers(viewControllers, direction: direction, animated: animated, completion: completion)
}
}
}
How to Use:
Replace setViewControllers
with setViewControllersPatched
.