SRL SRL - 3 months ago 12
Swift Question

Switching Views Programmatically in Swift

I am trying to switch to the second view by pressing the "feeling lucky" button. When I try out my simulator and press it, it just goes to a black screen. How could I fix this?

@IBAction func FeelingLuckyPress(sender: UIButton) {

let secondViewController:SecondViewController = SecondViewController()

self.presentViewController(secondViewController, animated: true, completion: nil)
}

Rob Rob
Answer

You can add a segue between the two scenes in your storyboard by control dragging from the view controller icon at the top of the first scene to the second scene:

create segue

You can then select that segue and give it a unique storyboard identifier, and then you can just perform the segue using that identifier:

performSegueWithIdentifier("SegueToSecond", sender: self)

Alternatively, you can do something like:

let controller = storyboard?.instantiateViewControllerWithIdentifier("Second") as SecondViewController
presentViewController(controller, animated: true, completion: nil)

where "Second" is a storyboard identifier I specified for that destination scene in Interface Builder.


By the way, there are alternatives if you're creating your destination scene programmatically or using NIBs, but storyboards are more common, so I focused on that in my examples above.

Comments