Button that takes to new view controller does not work

I am building a simple app that has 2 view controller and a navigation controller to link those 2.

I have a button that takes me to the second view controller

But when I click on the button nothing happens! I have made an IBAction for it with this code inside:

@IBAction func fightButton(_ sender: UIButton) {

        

        if let vc = storyboard?.instantiateViewController(withIdentifier: "Battle") as? BattleViewController {
                    navigationController?.pushViewController(vc, animated: true)
        }

    }

How can I fix this?

I would check a few things first.

  1. Is the func called ?

  2. if the vc instantiated ?

  3. Is the pushView called ?

So, I would instrument the code :

@IBAction func fightButton(_ sender: UIButton) {

        print("fightButton called")

        if let vc = storyboard?.instantiateViewController(withIdentifier: "Battle") as? BattleViewController {
              print("BattleViewController instantiated")
              print("navigationController", navigationController)
              navigationController?.pushViewController(vc, animated: true)
        }

    }

Please tell exactly what you get.

Note that if you have defined a segue directly from the button, the IBAction will not be called.

I have actually solved the problem. I have found that Xcode did not detect the navigation controller and as I have used optional chaining, the code did not get executed.

I have fixed the problem, by simply deleting and adding the Navigation Controller again.

Thanks for the help

How and where is navigationController defined ? Is it defined in BattleViewController ?

I would not delete and recreate the Navigation Controller. But better find it. Try what is explained here: https://stackoverflow.com/questions/25053846/swift-how-do-i-get-access-to-the-navigationcontroller-in-appdelegate

let navigationController = self.window?.rootViewController as! UINavigationController
Button that takes to new view controller does not work
 
 
Q