1

I'm building a game in Swift 5 programmatically and want to navigate from the main menu to the game screen. Here is my code:

func handleButtonsTapped() {
    playButton.addTarget(self, action: #selector(pushGameViewController), for: .touchUpInside)
}

And the selector to handle pushing the view controller when tapped:

@objc func pushGameViewController() {
    let destinationVC = GameViewController()
    navigationController?.pushViewController(destinationVC, animated: true)
}

When I tap the button in simulator nothing happens. I have handleButtonsTapped() called in my viewDidLoad() function as well.

c0ded_truth
  • 37
  • 1
  • 2
  • 8

4 Answers4

1

Got an answer!

In my SceneDelegate.swift I set:

let menuViewController = UINavigationController(rootViewController: MenuViewController())
window?.rootViewController = menuViewController

Now it works! Thanks for the comments everyone :)

c0ded_truth
  • 37
  • 1
  • 2
  • 8
1

You can not initialize a storyboard view controller outlet directly. Rather you can load it from the bundle where your storyboard takes place. Follow this belowing steps.

  1. First of all set Storyboard Id 'GameViewController'(according to screenshot).
  2. Then replace the pushGameViewController function by the below one.

    @objc func pushGameViewController() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController")
        self.navigationController?.pushViewController(destinationVC, animated: true)
    }
    

enter image description here

AMIT
  • 906
  • 1
  • 8
  • 20
1
@objc func pushGameViewController() {
    let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController") as! GameViewController
    navigationController?.pushViewController(destinationVC, animated: true)
}

Be sure to give your view controller a storyboard id called GameViewController in the interface builder

Eyad Shokry
  • 151
  • 1
  • 9
0

This is my code and this can running.

Is your ViewController set for UINavigation?

@IBOutlet weak var playButton: UIButton!

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

func handleButtonsTapped() {
    playButton.addTarget(self, action: #selector(pushGameViewController), for: .touchUpInside)
}

@objc func pushGameViewController() {
    let destinationVC = GameViewController()
    navigationController?.pushViewController(destinationVC, animated: true)
}
Su Justin
  • 11
  • 1