Search code examples
swiftxcodeuiviewuiviewcontrolleruiviewanimationtransition

Problem with animation when using UIView.transition & UIView.AnimationOptions when transitioning between ViewControllers


I'm using Swift and attempting to transition between a Menu screen ViewController (LaunchViewController) and a Game ViewController (InGameViewController) using the below code. However, whilst the transition works okay, no matter what animation options I use (currently using .transitionCrossDissolve) the animation always appears from the top left expanding to fill the whole screen. I can change the duration and the animation adjusts as expected, but no matter what the UIView.AnimationOption I use it always uses the same animation.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "InGameViewController")
vc.view.frame = (self.view?.frame)!
vc.view.layoutIfNeeded()

UIView.transition(with: self.view!, duration: 0.3, options: .transitionCrossDissolve, animations: {

            self.view?.window?.rootViewController = vc

        }, completion: { (true) in

        })

How can I make this transition animation as desired? Many thanks in advance


Solution

  • func changeRootViewControllerTo(_ controller: UIViewController, animated: Bool = false) {
    
        UIApplication.shared.keyWindow?.rootViewController = controller
    
        guard
            animated,
            let window = UIApplication.shared.keyWindow else {
                return
        }
    
        UIView.transition(with: window,
                          duration: 0.3,
                          options: .transitionCrossDissolve,
                          animations: nil,
                          completion: nil)
    }
    

    In my case this works perfect. I don't think you need to add those lines
    vc.view.frame = (self.view?.frame)! vc.view.layoutIfNeeded()
    and change self.view to window in transition method.