AndroidDev
AndroidDev

Reputation: 21237

Can't segue from button to UINavigationController

I'm getting an error when trying to execute a segue from a button to a UINavigatinController:

fatal error: unexpectedly found nil while unwrapping an Optional value

@IBAction func displayFootball(_ sender: Any) {
        self.configToSend = self.configFootball
        performSegue(withIdentifier: "navSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "navSegue" {
        let navVC = segue.destination as! UINavigationController
        let mainVC = navVC.topViewController as! MainViewController //<--This is where the error occurs

        mainVC.config = self.configToSend
    }
}

enter image description here

The first segue is called 'navSegue' and the second is unnamed. Both go directly from one view controller to the next (not from the buttons themselves).

enter image description here

The navVC is NOT nil, btw.

Anyone know why this is happening? Thank you.

Upvotes: 1

Views: 115

Answers (1)

Giuseppe Sapienza
Giuseppe Sapienza

Reputation: 4708

To achieve this, try to use:

let navVC = segue.destination as? UINavigationController
(navVC.viewControllers[0] as? YourVCClass).property = dataToSend

Edit:

The problem of nil on viewControllers array could be because you haven't a relationship segue from NavigationController to his first ViewController

The icon of the segue should be like this one:

Upvotes: 3

Related Questions