How to propagate the action from SKScene component to UIViewController

21 Views Asked by At

in XCode 12, using Swift 5, create a new Project using the Game SpriteKit technology. That generates amongst other things:

  • GameViewController.swift
  • GameScene.swift

In GameScene.swift I added

  1. after the class definition

    let tapRec2 = UITapGestureRecognizer()
    
  2. in override func didMove(to view: SKView) {

    tapRec2.addTarget(self, action:#selector(GameScene.tappedView2(_:) ))
    tapRec2.numberOfTouchesRequired = 1
    tapRec2.numberOfTapsRequired = 2  //2 taps i
    self.view!.addGestureRecognizer(tapRec2)
    
  3. the implementation of tappedView2 function to detect a double tap.

    @objc func tappedView2(_ sender:UITapGestureRecognizer) {
      let controller = self.view?.window?.rootViewController
      let new_controller = ViewController()
      print("double click detected")
      controller?.navigationController?.pushViewController(new_controller, 
      animated: true)
    }
    

I compiled it and run it, the app starts appropriately and if I do a double click it detects it, however no ViewController is displayed. What am I doing wrong ?

1

There are 1 best solutions below

1
Luca Toldo On

found the solution by simplifying tappedView2 to the following code:

  @objc func tappedView2(_ sender:UITapGestureRecognizer) {
    let new_controller = ViewController()
    self.view?.window?.rootViewController = new_controller
  }

and simplified the UIViewController to:

  import UIKit
  import Foundation
  class ViewController: UIViewController  {

      override func viewDidLoad() {
         super.viewDidLoad()
      }
  }