swiftuiviewcontrollersprite-kitskscene

Moving from SKScene to ViewController


I want to move from my SKScene to a view controller when I touch a SKSpriteNode and back to SKScene when I touch a UIButton. It is working from view controller to SKScene and also the other way around, but only the first time. When I then go back to my scene and the move to the view controller again (the second time), I can hear the music, and it prints everything from viewDidLoad, but it does not the show me UI Elements. I dismissed the scene so that might not be the problem.

Here is the code for moving back from the scene to the view controller.

let currentViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!        
currentViewController.present(ViewController(), animated: false, completion: nil)

or

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier :"VC")
let currentViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!

currentViewController.present(viewController, animated: false, completion: nil)

Solution

  • Replace the code related to currentViewController with this:

    self.view?.window?.rootViewController?.present(viewController, animated: true, completion: nil)
    

    It should work. You can also create a segue in Storyboard and call it like this:

    self.view?.window?.rootViewController?.performSegue(withIdentifier: "VC", sender: self)
    

    EDIT:

    I've tried on one of my app now the next solution and it worked:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "VC")
    vc.view.frame = rootViewController.view.frame
    vc.view.layoutIfNeeded()
    
    UIView.transition(with: window, duration: 0.3, options: .transitionFlipFromRight, animations:
            {
            window.rootViewController = vc
        }, completion: { completed in
            // maybe do something here
        })
    

    To me it worked, I hope it will solve your case :)