c0ded_truth
c0ded_truth

Reputation: 37

Push new view controller when button is pressed

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.

Upvotes: 1

Views: 4113

Answers (4)

Eyad Shokry
Eyad Shokry

Reputation: 151

@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

Upvotes: 1

AMIT
AMIT

Reputation: 924

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

Upvotes: 1

c0ded_truth
c0ded_truth

Reputation: 37

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 :)

Upvotes: 1

Su Justin
Su Justin

Reputation: 11

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)
}

Upvotes: 0

Related Questions