Exploring segue from storyboard to code and presenting view controllers
@IBAction func rollTheDice() {
// Get the DiceViewController
let controller: DiceViewController
controller = storyboard?.instantiateViewController(withIdentifier: "DiceViewController") as! DiceViewController
// Set the two values to random numbers from 1 to 6
controller.firstValue = randomDiceValue()
controller.secondValue = randomDiceValue()
// Present the view Controller
present(controller, animated: true, completion: nil)
}
^ Above sets up new ViewController, passes data AND presents new ViewController
Above only sets up the Segue and New ViewController but does not connect two ViewControllers
Notice that:
In the RollViewController file, the rollTheDice method is empty.
In the Storyboard file, a segue connects the rollTheDice Button directly to the DiceViewController.
In the attributes inspector, the segue is given the identifier, “rollDice”.
Again, this only sets up the Segue and hides the instantiation of the new ViewController behind the story board, but does not pass data.
We need to override the func prepare(for segue: UIStoryboardSegue, sender: Any?) method
We then cast DiceViewController
as the segue.destination
and then can pass the data to the ViewController that presents the dice.
Use if segue.identifier == "nameOfSegue" {
when we have more than one segue attached to a single ViewController