使用自定义转换时,如何在呈现UIViewController中处理方向更改

时间:2018-02-06 22:01:09

标签: ios iphone ipad uiviewcontroller

我有一个UIViewController作为根视图控制器,它使用自定义转换呈现另一个UIViewController。在查看子视图控制器的同时旋转设备,然后返回到根视图控制器时,根视图控制器的视图框架不会更新。我已将其缩小到自定义转换的存在,即如果您没有自定义转换,它可以正常工作。拥有自定义转换并让根视图控制器处理方向更改的最佳方法是什么?

我在这里有一个演示项目:https://github.com/rawbee/TestOrientation

1 个答案:

答案 0 :(得分:1)

似乎您忘记为正在呈现的视图控制器设置框架:

toVC.view.frame = fromVC.view.frame

只需将此行添加到animateTransition,以便该方法如下所示:

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    guard let fromVC = transitionContext.viewController(forKey: .from),
        let toVC = transitionContext.viewController(forKey: .to),
        let snapshot = fromVC.view.snapshotView(afterScreenUpdates: false)
        else { return }

    let containerView = transitionContext.containerView

    // you want the newly presented view to have the same frame as the old one
    toVC.view.frame = fromVC.view.frame

    containerView.addSubview(toVC.view)
    containerView.addSubview(snapshot)

    let animator = UIViewPropertyAnimator(duration: transitionDuration(using: transitionContext), curve: .easeInOut) {
        snapshot.alpha = 0.0
    }
    animator.addCompletion { _ in
        snapshot.removeFromSuperview()
        transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
    }
    animator.startAnimation()
}