Switching Views Programmatically in Swift
Asked Answered
B

1

9

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)
}
Bethlehem answered 25/12, 2014 at 19:32 Comment(2)
Where is SecondViewController supposed to get its view from? To put it another way, what you have done so that this view should not be a black screen? Explain. Describe.Corkhill
Here are the ways a view controller gets its view. If you don't use one of them, the view controller's view is empty and black: apeth.com/iOSBook/ch19.html#_view_controller_and_view_creationCorkhill
B
24

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:

performSegue(withIdentifier: "SegueToSecond", sender: self)

Alternatively, you can do something like:

guard let controller = storyboard?.instantiateViewController(withIdentifier: "Second") as? SecondViewController else {
    return
}
present(controller, animated: true) // or `show(controller, sender: self)`

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


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

Bron answered 25/12, 2014 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.